如何在非关键字段上使用Linq连接

时间:2013-12-09 10:12:40

标签: linq entity-framework

这是一个简化的例子

public class Book
{
    public string BookId
    public string AuthorName

}

public class Author
{
    public string Name
}

public class BookWithAuthor
{
    public Book Book;
    public Author Author;
}

为了这个例子,不可能给Author一个Id并将其用作外键。

List<Book> books = _unitOfWork.BookRepo.Get.ToList();
List<Author> authors= _unitOfWork.AuthorRepo.Get.ToList();

我正在尝试在Author.Name/Book.AuthorName字段上编写LINQ连接并返回BookWithAuthor的List。到目前为止,我所有的尝试都失败了,通常无法确定“连接参数......”

2 个答案:

答案 0 :(得分:1)

使用以下

List<Book> books = _unitOfWork.BookRepo.Get.ToList();
List<Author> authors= _unitOfWork.AuthorRepo.Get.ToList();
List<BookWithAuthor> lst = 
    (from c in books
    join d in authors on new {Aname = c.AuthorName } equals new {Aname = d.Name } into cd
    from tcd in cd.DefaultIfEmpty()
    select new BookWithAuthor
    {
        Book = c,
        Author = tcd
    }).ToList();

答案 1 :(得分:0)

这应该这样做:

var results = _unitOfWork.BookRepo.Get
    .Join(_unitOfWork.AuthorRepo.Get,
        book => book.AuthorName,
        author => author.Name,
        (book, author) => new BookWithAuthor
        {
            Book = book,
            Author = author
        })
    .ToList();