实体框架lambda查询以从其他表获取信息

时间:2019-04-11 09:28:15

标签: c# sql entity-framework

我正在使用实体框架lambda查询从表中获取数据:

db.Orders.Where(x => x.OrderID == orderid)
         .Select(x => new JOrders 
         { 
             id = x.OrderID, 
             customer_id = x.CustomerID, 
             product_id = x.ProductID,  
             account_id = x.AccountID
         }).toList()

CustomerIDProductIDAccountID是来自单独表(即分别为Customers, Products, Accounts)的主键。我想从它们各自的表中获取这些ID的“名称”列,并将其返回。我正在寻找一种优化的lambda查询,因为返回的记录数可能是数千。

2 个答案:

答案 0 :(得分:1)

如果您未在EF中建立关联,则可以像这样手动加入

db.Orders.Where(x => x.OrderID == orderid)
.Join(db.Customers,Order => Order.OrderID, Customer => Customer.CustomerID, (Order, Customer) => new {OrderID = Order.id, CutomerName = Customer.Name, more fields..}).ToList()

但是如果您确实有一个关联表,您可以直接调用它

db.Orders.Where(x => x.OrderID == orderid)
         .Select(x => new JOrders 
         { 
             id = x.OrderID, 
             customer_id = x.CustomerID, 
             product_id = x.ProductID,  
             account_id = x.AccountID,
             name = x.Customers.Name
         }).toList()

答案 1 :(得分:1)

如果您在Orders类中正确设置了导航属性。只需在查询中包括它们,然后就可以在lambda中使用这些属性。像这样:

db.Orders
.Include(x => x.Customer)
.Include(x => x.Product)
.Include(x => x.Account)
.Where(x => x.OrderID == orderid)
         .Select(x => new JOrders 
         { 
             id = x.OrderID, 
             customer_name = x.Customer.Name, 
             product_name = x.Product.Name,  
             account_name = x.Account.Name
         }).toList()

但是我相信您在Products中将有多个Order,因此您可能需要相应地进行更改。