我有两个表订单,与Customers表相关的汽车。在查询三个表时我得到重复而不是每个客户的单个值。结果查询对我来说有点混乱,你会如何处理这种情况。我正在使用“ViewModel”=模型来索引,创建,编辑,删除客户信息。
public class ProductVM
{
//Products
public int ProductID { get; set; }
public string Name { get; set; }
public Nullable<int> Supplier_ID { get; set; }
public string Description { get; set; }
public string Product_Code { get; set; }
//Specifications
public int ID { get; set; }
public string Bullet_Point { get; set; }
public string Bullet_Point1 { get; set; }
public Nullable<int> Product_ID { get; set; }
}
以下是编辑功能。
[HttpGet]
public ActionResult Edit(int? id){
List<CustomerVM> CustomerVMlist = new List<CustomerVM>(); // to hold list of Customer and order details
var customerlist =(from Cust in db.Customers
join Ord in db.Orders on Cust.CustomerID equals Ord.CustomerID
join auto in db.AutoMobiles on Cust.CustomerID equals auto.CustomerID
where Cust.CustomerID==1
select new { Cust.Name, Cust.Mobileno, Cust.Address, Ord.OrderDate, Ord.OrderPrice,auto.Vehicle_Type}).ToList();
foreach (var item in customerlist) {
CustomerVM VMOBJ = new CustomerVM();
VMOBJ.Name= item.Name;
VMOBJ.Mobileno = item.Mobileno;
VMOBJ.Address = item.Address;
VMOBJ.OrderDate = item.OrderDate;
VMOBJ.OrderPrice = item.OrderPrice;
VMOBJ.Vehicle_Type = item.Vehicle_Type;
CustomerVMlist.Add(VMOBJ);
}
return View(CustomerVMlist);
}
答案 0 :(得分:0)
您真正希望使用此查询完成什么? 您发布的查询有2个内部联接,从客户到订单,从客户到汽车。因此,当客户下达两个订单时,客户将在结果中出现两次。有时,首先在SQL Management Studio中使用常规创建查询,然后将其转换为LINQ。
如果您需要已下订单的所有客户的列表,并希望添加结果中包含的最后一个订单,您可以这样做:
List<CustomerVM> customerList = (
from cust in db.Customers
let lastOrder = (
from ord in db.Orders
where ord.CustomerID == cust.CustomerID
orderby ord.OrderDate descending
).FirstOrDefault()
let automobile = (
from auto in db.Automobiles
where auto.CustomerID == cust.CustomerID
).FirstOrDefault()
select new CustomerVM {
Name = Cust.Name,
Mobileno = Cust.Mobileno,
Address = Cust.Address,
OrderDate = lastOrder.OrderDate,
OrderPrice = lastOrder.OrderPrice,
Vehicle_Type = automobile.Vehicle_Type
}
).Tolist();
return View(customerList);