2012-08-04 44 views
1

使用我試圖做一些同樣的事情一個大EF4模型結果的外鍵引用,可在LINQ2SQL使用單獨的dbml的完成。一個基本的問題,我遇到了,這很可能代表了我一個非常缺乏基本的LINQ to實體的知識,就是你怎麼使用結果的引用來查找引用表中的對象?EF4模型通過使用LINQ to實體

例如,我有4個表即都通過外鍵連接在一起。

從概念上講,我可以跳過所有使用foreach對結果引用的表,但它看起來很笨拙,下面的代碼如何使用linq來代替?

  //Get book 
      var book= db.books.SingleOrDefault(d => d.bookId == 286); 

      //If no book, return 
      if (book == null) return null; 

      //Get the shelf associated with this book 
      List<shelf> slist = new List<shelf>(); 

      foreach (reading r in book.readings) 
      { 
       foreach (event re in r.events) 
       { 
        slist.Add(re); 
       } 
      } 
      List<event> bookevents = slist.Distinct().ToList(); 

      //Get the customers associated with the events 
      List<int> clist = new List<int>(); 

      foreach (event eb in bookevents) 
      { 
       var cust = db.customers.Where(c => c.customerID == eb.inID || c.customerID == eb.outID).ToList(); 
       clist.AddRange(cust.Select(c => c.customerID)); 
      } 

      //Return the list of customers 
      return clist; 

編輯: 我得到了它下降到3步,萬一這張貼其他人遇到類似的問題。我歡迎對如何做到這一點更優雅

 //Get book 
     var book= db.books.SingleOrDefault(d => d.bookId == 286); 

     //If no book, return 
     if (book == null) return null; 

     //Get the bookevents associated with this book 
     var bookevents = (from reading in book.readings 
        select reading.events).SelectMany(e => e).Distinct(); 

     //Get the customers associated with the events 
     var clist = (from be in bookevents 
        from c in db.customers 
        where c.customerID == be.inID || c.customerID == be.outID 
        select c.customerID).ToList(); 

     //Return the list of customers 
     return clist; 

回答

2

試試這個任何意見:

var distinctEvents = (from event in db.events 
       join reading in db.readings on event.readingID equals reading.readingID 
       where reading.bookID == 286 
       select event).Distinct(); 
       // if you want to see this bookID is present in Book table, you should add a join statement like "join book in db.books on reading.bookID == book.bookID" 
var custIdList = from c in db.customers 
       from event in distinctsEvents 
       where c.customerID == event.inID || c.customerID == be.outID 
       select c.customerID; 

return custIdList.ToList(); 
+0

沒問題,告訴我,如果你需要更多的提示。如果這個工作適合你,你可以將其標記爲答案。 – Ashkan 2012-08-04 20:03:41