linq到实体查询的右外连接

时间:2016-02-28 05:34:19

标签: c# join ef-code-first linq-to-entities

每个Order生成一些RoutingStep个,每个步骤都包含Operation,每个操作都在Workshop中进行。

public class Order
{
   public int Id {get; set;}
   public string OrderNumber {get; set;}
   public virtual collection<Routing> Routings{get; set;}
}
public class Routing
{
   public int Id {get; set;}
   public virtual Order Order {get; set;}
   public virtual Operation Operation{get; set;}
}
public class Operation
{
   public int Id {get; set;}
   public virtual Workshop Workshop{get; set;}
}
public class Workshop
{
   public int Id {get; set;}
   public string Title {get; set;}
}

我想写一个linq到实体查询(方法语法)来了解Workshop s并且没有传递Workshop s的每个订单传递。换句话说 如果我完全有4 Workshop个且O1包含3个Routing步骤,我想要O1的结果:

------------------------------
| Order  |  Workshop | status |
------------------------------
|   O1   |   W1      |  pass  |
------------------------------
|   O1   |   W2      |  pass  |
------------------------------
|   O1   |   W3      |not pass|
------------------------------
|   O1   |   W4      |  pass  |
-------------------------------

我写下面的代码

var query = db.Orders
    .SelectMany(order=> order.Routings
    .Select(g => new
    {
        Number = g.Order.OrderNumber,
        Workshop = g.Operation.Workshop.Title,
        Status = g.????
    }).ToList();

我应该使用哪种代码&#34; ???&#34; ?

1 个答案:

答案 0 :(得分:1)

var query = db.Orders
    .SelectMany(x => db.Workshops, (x, y) => new { Order = x, Workshop = y }) // all combinations of orders with workshops
    .GroupJoin( // left join to determine whether each combination actually exists
        db.Routings,
        x => x,  // proposed order-workshop pair
        y => new { Order = y.Order, Workshop = y.Operation.Workshop }, // existing order-workshop pair
        (x, ys) => new
        {
            x.Order.OrderNumber,
            x.Workshop.Title,
            Status = ys.Any() ? "pass" : "not pass"
        });