2017-04-04 69 views
0

假設我有我的數據庫三個表:LINQ查詢

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

我需要寫一個傳入參數INT [] authorsIds並返回所有書籍的方法(同上,BookName,這本書的作者列表),如果它是由其Id包含在int [] authorsIds參數中的任何作者編寫的。

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

我真的需要幫助。非常感謝你的幫助。

回答

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表(或可能具有不同的名稱)。

+0

嗨克里斯蒂安,謝謝你的幫助,但我想我只會得到書籍專欄(Id,BookName)。我還需要得到AuthorsList - 這本書的作者名單。 – user2925794

+0

請張貼你的'書籍'模型。 –

0

這個答案是基於精確的結構沒有考慮到一個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) 

這將propably有語法錯誤和糾正你可能會得到大約已經有一個多線程的錯誤後回答這裏