Note that there are some explanatory texts on larger screens.

plurals
  1. POEF4 model referencing through result foreign keys using linq to entities
    primarykey
    data
    text
    <p>Using one big EF4 model I'm trying to do some of the same things, that can be done in linq2sql using separate dbml's. A basic issue I have run into, which is likely a very fundamental lack of knowledge of linq to entities on my behalf, is how do you use result references to find objects in tables that are referenced?</p> <p>Example, I have 4 tables that are all linked together through foreign keys.</p> <p>Conceptually I can hop through all of the tables using foreach on the result references, however it seems pretty clumsy, how could below code be written using linq instead?</p> <pre><code> //Get book var book= db.books.SingleOrDefault(d =&gt; d.bookId == 286); //If no book, return if (book == null) return null; //Get the shelf associated with this book List&lt;shelf&gt; slist = new List&lt;shelf&gt;(); foreach (reading r in book.readings) { foreach (event re in r.events) { slist.Add(re); } } List&lt;event&gt; bookevents = slist.Distinct().ToList(); //Get the customers associated with the events List&lt;int&gt; clist = new List&lt;int&gt;(); foreach (event eb in bookevents) { var cust = db.customers.Where(c =&gt; c.customerID == eb.inID || c.customerID == eb.outID).ToList(); clist.AddRange(cust.Select(c =&gt; c.customerID)); } //Return the list of customers return clist; </code></pre> <p>EDIT: I got it down to 3 steps, posting this in case other people run into similar issues. I welcome any comments on how to do this more elegantly</p> <pre><code> //Get book var book= db.books.SingleOrDefault(d =&gt; 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 =&gt; 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; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload