具有多对多关系的linq查询

时间:2017-04-04 16:35:23

标签: linq

假设我的数据库中有三个表:

Authors(PK Id, AuthorName) 
Books(PK Id, BookName) 
Authors_Books(FK BookId, FK AuthorId)

我需要编写一个传入参数int [] authorsIds的方法,并返回所有书籍(Id,BookName,本书作者列表),如果它是由任何作者编写的,其ID包含在int [] authorsIds参数中

我需要LINQ查询(查询方法)。

我真的需要帮助。非常感谢你的帮助。

2 个答案:

答案 0 :(得分:1)

var int[] authors = { 1, 2, 3 };
var books = from book in books
            where book.Authors.Any(x => authors.Contains(x.AuthorId))
            select book;

PS:我认为book.Authors是您对Authors_Books表的引用(或者可能有不同的名称)。

答案 1 :(得分:0)

这个答案是基于确切的结构而不考虑A obj在其结构中有B

var book = from b in books 
           where book.Id in ( from ab in AuthersBooks 
                               where selectedAuthers.contains(ab.AutherId)
                               select ab.bookId ) //now we have books that are authered by one of the selected authers
           select new { BookId = b.Id, // now we create an anonymos object to contain any info we need
                        BookName = b.Name,
                        BookAuthers = (from a in authers
                                       join ab in AuthersBooks
                                       on a.Id == ab.AuthersId
                                       where ab.bookid == b.Id
                                       select a)

这可能会出现语法错误,并且在纠正之后您可能会收到有关已经有答案的多个线程的错误