Note that there are some explanatory texts on larger screens.

plurals
  1. POLINQ-to-entities generic == workaround
    primarykey
    data
    text
    <p>I have a following LINQ-to-entities query</p> <pre><code>IQueryable&lt;History&lt;T&gt;&gt; GetFirstOperationsForEveryId&lt;T&gt; (IQueryable&lt;History&lt;T&gt;&gt; ItemHistory) { var q = (from h in ItemHistory where h.OperationId == (from h1 in ItemHistory where h1.GenericId == h.GenericId select h1.OperationId).Min() select h); return q; } </code></pre> <p><code>ItemHistory</code> is a generic query. It can be obtained in the following way</p> <pre><code>var history1 = MyEntitiySet1.Select(obj =&gt; new History&lt;long&gt;{ obj.OperationId, GenericId = obj.LongId }); var history2 = AnotherEntitiySet.Select(obj =&gt; new History&lt;string&gt;{ obj.OperationId, GenericId = obj.StringId }); </code></pre> <p>In the end of all I want a generic query being able to work with any entity collection convertible to <code>History&lt;T&gt;</code>.</p> <p>The problem is the code does <strong>not compile</strong> because of GenericId comparison in the inner query (Operator '==' cannot be applied to operands of type 'T' and 'T').</p> <p>If I change == to <code>h1.GenericId.Equals(h.GenericId)</code> I get the following <code>NotSupportedException</code>:</p> <blockquote> <p>Unable to cast the type 'System.Int64' to type 'System.Object'. LINQ to Entities only supports casting Entity Data Model primitive types.</p> </blockquote> <p>I've tried to do grouping instead of subquery and join the results.</p> <pre><code>IQueryable&lt;History&lt;T&gt;&gt; GetFirstOperationsForEveryId&lt;T&gt; (IQueryable&lt;History&lt;T&gt;&gt; ItemHistory) { var grouped = (from h1 in ItemHistory group h1 by h1.GenericId into tt select new { GenericId = tt.Key, OperationId = tt.Min(ttt =&gt; ttt.OperationId) }); var q = (from h in ItemHistory join g in grouped on new { h.OperationId, h.GenericId } equals new { g.OperationId, g.GenericId } select h); return q; } </code></pre> <p>It compiles because GenericId's are compared with <code>equals</code> keyword and it works but the query with real data is too slow (it has been running for 11 hours on dedicated postgresql server).</p> <p>There is an option to build a whole expression for the outer where statement. But the code would be too long and unclear.</p> <p>Are there any simple workarounds for equality comparison with generics in LINQ-to-entities?</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.
    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