left使用linq连接2个表
本文关键字:2个表 连接 linq 使用 left | 更新日期: 2023-09-27 18:00:02
我有一个linq查询,需要它进行左联接而不是内部联接。我看到的所有例子都只剩下1个join,但当我尝试用2个时,我没能把它做好。那么,这将如何更改为使用2个左联接呢?
ruleSets = (from rs in db.RuleSets
join brs in db.BatchRuleSets on rs.ID equals brs.RuleSetID
join b in db.Batches on brs.BatchID equals b.id
where !clientId.HasValue || b.ClientID == clientId.Value
where !batchId.HasValue || brs.BatchID == batchId.Value
select new
{
rs.ID,
rs.Description,
rs.IsActive,
rs.CreatedDate,
rs.EffectiveDate,
rs.ExpirationDate,
BatchName = b.FileName,
b.ClientID
}).ToList().Select(x => new {
x.ID,
x.Description,
x.IsActive,
x.CreatedDate,
x.EffectiveDate,
x.ExpirationDate,
x.BatchName,
ClientName = GetClientName(x.ClientID)});
在linq中使用左联接,如下所示。。。。
join t in Web
on websites.WebsiteID equals t.WebsiteID
into wt1
from wt in wt1.DefaultIfEmpty()
在此之后,wt将使用i其中的条件和select语句。。。。。。
通过使用这个概念,您可以在LINQ中进行左联接查询。。。。。
ruleSets = (from rs in db.RuleSets
join brs in db.BatchRuleSets on rs.ID equals brs.RuleSetID into j1
from jbrs in j1.DefaultIfEmpty()
join b in db.Batches on jbrs.BatchID equals b.id into j2
from jb in j2.DefaultIfEmpty()
where !clientId.HasValue || jb.ClientID == clientId.Value
where !batchId.HasValue || jbrs.BatchID == batchId.Value
select new
{
rs.ID,
rs.Description,
rs.IsActive,
rs.CreatedDate,
rs.EffectiveDate,
rs.ExpirationDate,
BatchName = jb.FileName,
jb.ClientID
}).ToList().Select(x => new {
x.ID,
x.Description,
x.IsActive,
x.CreatedDate,
x.EffectiveDate,
x.ExpirationDate,
x.BatchName,
ClientName = GetClientName(x.ClientID)});
void Main()
{
var customers = new List<Customer> {new Customer() { CustomerId = 1}, new Customer() { CustomerId = 2}};
var orders = new List<Order> {new Order() { OrderId = 1, CustomerId = 1}, new Order() { OrderId = 2, CustomerId = 1}};
var items = new List<Item> {new Item() { ItemId = 1, OrderId = 1}, new Item() { ItemId = 2, OrderId = 1}, new Item() { ItemId = 3, OrderId = 2}};
var doubleJoin = from customer in customers
join order in orders on customer.CustomerId equals order.CustomerId
into customerOrders
from co in customerOrders.DefaultIfEmpty()
where (co != null)
join item in items on co.OrderId equals item.OrderId
select new {Customer = customer, Orders = co, Items = item};
doubleJoin.Dump();
}
public class Customer
{
public int CustomerId { get; set; }
}
public class Order
{
public int OrderId { get; set; }
public int CustomerId { get; set;}
}
public class Item
{
public int ItemId { get; set; }
public int OrderId { get; set; }
}