LINQ to Entities - 将所有字段放入最终结果中

时间:2011-08-15 02:33:00

标签: c# linq-to-entities

我们以此查询为例(来自MSDN文档):

ObjectSet<SalesOrderHeader> orders = context.SalesOrderHeaders;
ObjectSet<SalesOrderDetail> details = context.SalesOrderDetails;

var query =
    from order in orders
    join detail in details
    on order.SalesOrderID equals detail.SalesOrderID
    where order.OnlineOrderFlag == true
    && order.OrderDate.Month == 8
    select new
    {
        SalesOrderID = order.SalesOrderID,
        SalesOrderDetailID = detail.SalesOrderDetailID,
        OrderDate = order.OrderDate,
        ProductID = detail.ProductID
    };

如果我想将“order”中的所有字段放入最终对象(即select new)以及详细信息中的其他字段,我该怎么做?

3 个答案:

答案 0 :(得分:1)

var query =
    from order in orders
    join detail in details
    on order.SalesOrderID equals detail.SalesOrderID
    where order.OnlineOrderFlag == true
    && order.OrderDate.Month == 8
    select new
    {
        SalesOrderHeader = order;
        SalesOrderDetail = detail;
    };

答案 1 :(得分:0)

您可以在查询中返回整个SalesOrderHeader对象,也可以使用Include方法。

ObjectSet<SalesOrderHeader> orders = context.SalesOrderHeaders;
ObjectSet<SalesOrderDetail> details = context.SalesOrderDetails;

var query =
    from order in orders
    join detail in details
    on order.SalesOrderID equals detail.SalesOrderID
    where order.OnlineOrderFlag == true
    && order.OrderDate.Month == 8
    select new
    {
        SalesOrderID = order.SalesOrderID,
        SalesOrderDetailID = detail.SalesOrderDetailID,
        OrderDate = order.OrderDate,
        ProductID = detail.ProductID,
        Order = order
    };

或者使用Include方法(假设您的SalesOrderHeader类具有对SalesOrderDetail类的集合引用):

ObjectSet<SalesOrderHeader> orders = context.SalesOrderHeaders;
ObjectSet<SalesOrderDetail> details = context.SalesOrderDetails;

var query =
    (from order in orders
    where order.OnlineOrderFlag == true
    && order.OrderDate.Month == 8
    select order).Include(x => x.Details);

答案 2 :(得分:0)

做这样的事情?

            var query =
            from order in orders
            join detail in details
            on order.SalesOrderID equals detail.SalesOrderID
            where order.OnlineOrderFlag == true
            && order.OrderDate.Month == 8
            select new
            {
                SalesOrderID = order.SalesOrderID,
                SalesOrderDetailID = detail.SalesOrderDetailID,
                OrderDate = order.OrderDate,
                ProductID = detail.ProductID,
                Order = order
            };