EF LINQ 查询 master-details 到新模型

EF LINQ query master-details into new model

有很多 EF master-detail 问题,我已经浏览了其中的大部分。我找不到任何解决我正在使用的语法方法的方法,包括将 EF 查询结果转换为新的业务模型,但我确信有办法。

这是从 DAL 发出的业务模型(header 属性未显示)

  public class Order : OrderHeader, IOrder
  {
        public virtual List<OrderDetail> OrderDetails { get; set; } = new List<OrderDetail>();
  }

这里是简化的查询以显示我面临的问题,即在提取订单的同时加载 OrderDetails 的 collection。我可以在加载 header 之后 运行 另一个查询,但这听起来很慢而且笨拙。

public async Task<List<Business.Models.Order>> GetSimplifyOrders()
    {
        var query = (from n in _context.SalesOrderHeaders
                join c in _context.Customers on n.CustomerId equals c.CustomerId
                join d in _context.SalesOrderDetails on n.SalesOrderId equals d.SalesOrderId
                     select new Business.Models.Order
                     {
                         SalesOrderNumber = n.SalesOrderNumber,
                         Customer = new Business.Models.Customer() 
                                { CompanyName = c.CompanyName, 
                                    FullName = $"{c.FirstName} {c.LastName}",
                                    EmailAddress = c.EmailAddress},

                         **OrderDetails = ??**

                     }).AsNoTracking()
                       .ToList<Business.Models.Order>();
        return query;
    }

有人可以帮助我使用特定语法来加载内联详细信息,如上所示吗?

您可以使用另一个内部 LINQ 查询来填充模型内部的集合,而不是在顶层执行 join

from n in _context.SalesOrderHeaders
join c in _context.Customers on n.CustomerId equals c.CustomerId
select new Business.Models.Order
{
    SalesOrderNumber = n.SalesOrderNumber,
    Customer = new Business.Models.Customer()
    {
        CompanyName = c.CompanyName,
        FullName = $"{c.FirstName} {c.LastName}",
        EmailAddress = c.EmailAddress
    },

    OrderDetails = 
        (from d in _context.SalesOrderDetails
        where n.SalesOrderId == d.SalesOrderId
        select new Business.Models.OrderDetail()
        {
            ...
        })
        .ToList()
}