Note that there are some explanatory texts on larger screens.

plurals
  1. PORe-use parts of a linq query
    primarykey
    data
    text
    <p>We have a program that uses Linq-To-Sql and does a lot of similar queries on our tables. In particular, we have a timestamp column, and we pull the most recent timestamp to see if the table has changed since our last query. </p> <pre><code>System.Data.Linq.Binary ts; ts = context.Documents .Select(r =&gt; r.m_Timestamp) .OrderByDescending(r =&gt; r) .FirstOrDefault(); </code></pre> <p>We repeat this query often on different tables that's relevant for the current form/query whatever. What I would like to do is create a "function" or something that can repeat the last 3 lines of this query (and ideally would work on every table). Here's what I would like to write:</p> <pre><code>System.Data.Linq.Binary ts; ts = context.Documents .GetMostRecentTimestamp(); </code></pre> <p>But I have no idea how to create this "GetMostRecentTimestamp". Also, these queries are never this simple. They usually filter by the Customer, or by the current order, so a more valid query might be </p> <pre><code>ts = context.Documents .Where(r =&gt; r.CustomerID == ThisCustomerID) .GetMostRecentTiemstamp(); </code></pre> <p>Any help? Thanks!</p> <hr> <h3>Update [Solution]</h3> <p>I selected Bala R's answer, here's the code updated so it compiles:</p> <pre><code>public static System.Data.Linq.Binary GetMostRecentTimestamp(this IQueryable&lt;Data.Document&gt; docs) { return docs .Select(r =&gt; r.m_Timestamp) .OrderByDescending(r =&gt; r) .FirstOrDefault(); } </code></pre> <p>The only drawback to this solution is that I will have to write this function for each table. I would have loved Tejs's answer, if it actually worked, but I'm not re-designing my database for it. Plus DateTime is a not a good way to do timestamps.</p> <hr> <h3>Update #2 (Not so fast)</h3> <p>While I can do a query such as Documents.Where( ... ).GetMostRecentTimestamp(), this solution fails if I try to do an association based query such as MyCustomer.Orders.GetMostRecentTimestamp(), or MyCustomer.Orders.AsQueryable().GetMostRecentTimestamp();</p>
    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.
 

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