public class JoinModel
{
public Book Book { get; set; }
public BookOrder BookOrder { get; set; }
}
public class Book
{
public int BookID { get; set; }
public string UniqueID{ get; set; }
public int Year { get; set; }
public int BookNumber { get; set; }
public int Value { get; set; }
}
public class BookOrder
{
public int BookOrderID { get; set; }
public string UniqueID{ get; set; }
public int Year { get; set; }
public int BookNumber { get; set; }
public DateTime OrderDate { get; set; }
}
尝试编写一个lambda表达式,它将执行左连接并返回一个列表。该列表应包含Books,但是 BookOrder可以为null。
我尝试过以下操作会导致构建错误:
无法隐式转换类型 “System.Collections.Generic.IEnumerable< ...&BookOrder GT;到..BookOrder 第5行存在显式转换(你是否错过了演员?)(红色 bko上的波浪)
我无法更改Book或BookOrder课程,因为这是第三方,即我必须参加下面列出的3个条件。
List<JoinModel> lstJoinModel = new List<JoinModel>();
Line 1 - lstJoinModel = Context.Books
Line 2 - .GroupJoin(Context.BookOrder,
Line 3 - bk => new { bk.UniqueID, bk.Year, bk.PostingId },
Line 4 - bko => new { bko.UniqueID, bko.Year, bko.BookNumber },
Line 5 - (bk, bko) => new JoinModel { Book = bk, BookOrder = bko })
Line 6 - .Where(r => r.Book.Value > 0).ToList();
答案 0 :(得分:1)
这是你的linq:
List<JoinModel> lstJoinModel = (from bk in Context.Books
join bko in Context.BookOrder on new { bk.UniqueID, bk.Year, bk.BookNumber } equals new { bko.UniqueID, bko.Year, bko.BookNumber }
into bd
from bd2 in bd.DefaultIfEmpty()
where bk.Value > 0
select new JoinModel { Book = bk, BookOrder = bd2 }
).ToList();
在这里,您将使用lambda表达式版本
List<JoinModel> lstJoinModel = Context.Books.GroupJoin(Context.BookOrder,
bk => new { bk.UniqueID, bk.Year, bk.BookNumber },
bko => new { bko.UniqueID, bko.Year, bko.BookNumber },
(x, y) => new { Book = x, BookOrder = y })
.SelectMany(x => x.BookOrder.DefaultIfEmpty(),
(x, y) => new JoinModel
{
Book = x.Book,
BookOrder = y
})
.Where(r => r.Book.Value > 0).ToList();