Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can i simplify this LINQ-To-Entity query, and make it dynamic
    text
    copied!<p>I have this query for getting data through Entity Framework, which works today. Thing is, i want to create the query dynamically, i.e build it up in blocks, but i can't figure out how exactly to do it. I believe if i can somehow save one of the values that i retrieve in the beginning i can do it, but now i retrieve it twice (probably a bit slow as well? Unless the compiler fixes it before quering). Makes sense? Here is the LINQ:</p> <pre><code>from d in db.trains where d.cancelled &amp;&amp; d.station == toStation &amp;&amp; d.date &gt;= fromDate.Date &amp;&amp; d.date &lt;= toDate.Date &amp;&amp; (from k in db.trains where k.date == d.date &amp;&amp; k.trainId == d.trainId &amp;&amp; k.stationId == fromStation &amp;&amp; k.position &lt;= d.position select k.trainId).Contains(d.trainId) select new { trainId = d.trainId, date = d.date, arrival = d.arrival, departure = (from k in db.trains where k.date == d.date &amp;&amp; k.trainId == d.trainId &amp;&amp; k.stationId == fromStation &amp;&amp; k.position &lt;= d.position select k.departure).FirstOrDefault() } ); </code></pre> <p>So you see, in order to get the departure, i have to retrieve the same thing again. So what i'm asking is can i save the object in the first query and then retrieve it later somehow? I can't get the syntax working. </p> <p>The database looks something like this:</p> <pre><code>trainId stationId date arrival departure position 1 99 2010-10-11 10:00 10:10 1 1 98 2010-10-11 11:20 11:30 2 1 47 2010-10-11 12:30 12:40 3 2 99 2010-10-10 15:00 15:10 5 </code></pre> <p>etc</p> <p>So bascially, i need to retrieve two objects from the db, where the first one has stationId x and the other one has stationId y and both have the same date and trainId, and they have to be in the proper order, based on position (trains go both ways, but with different trainId's).</p> <p>Also, i would like to do be able to build this query dynamically, like this:</p> <pre><code>var trains = from d in db.trains select d; if (id &gt; 0) trains = trains.Where(p =&gt; p.trainId == id); if (date != DateTime.MinValue) trains = trains.Where(p =&gt; p.date == date); var items = (from train in trains).ToList(); </code></pre> <p>I.e based on if various variables have values.</p>
 

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