2012-08-04 47 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