Note that there are some explanatory texts on larger screens.

plurals
  1. POCan I create a LINQ-to-Entity query on non-Entity Member fields
    primarykey
    data
    text
    <p>I have an Entity class that I have extended using the <code>partial class</code> syntax to have some derived properties. I would like to perform a query using the <code>IQueryable&lt;T&gt;</code> interface that uses the information from these fields, but I currently get an exception that states</p> <blockquote> <p>The specified type member 'Title' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.</p> </blockquote> <p>Here are the relevant code snippets. You may assume that the Entity object has a String member named <code>Id</code>. </p> <pre><code>public partial class MyEntityObject { public String Title { get { return MyStrings.ResourceManager.GetString(Id) ?? ""; } } } /** * Throws exception trying to sort on the 'Title' field of a 'MyEntityObject' */ public IEnumerable&lt;T&gt; Query&lt;T&gt;(String fieldName, int low, int high) { // Get the ObjectContext&lt;T&gt; using a Repository pattern var query = context.GetRepository&lt;T&gt;() // Create an OrderBy clause based on the field by dynamically building an expression tree // see http://stackoverflow.com/questions/4546463/help-with-linq-and-generics-using-getvalue-inside-a-query PropertyInfo propertyInfo = typeof(T).GetProperty(fieldName); ParameterExpression e = Expression.Parameter(typeof(T), "e"); MemberExpression mexpr = Expression.MakeMemberAccess(e, propertyInfo); IQueryable&lt;T&gt; sortedQuery = query.OrderBy(Expression.Lambda&lt;Func&lt;T,Object&gt;&gt;(mexpr, e)); return sortedQuery.Skip(low).Take(high - low + 1).AsEnumerable(); } </code></pre> <p>As a last resort I can always do the <code>AsEnumerable()</code> before the <code>Skip</code> and <code>Take</code>, but that will involve retrieving <strong>all</strong> of the objects from the database even if the selection can be done by SQL.</p> <p>Perhaps the best alternative is to use reflection to check that the object property has a <code>DataMemberAttribute</code> and then chose to do either <code>query.OrderBy().Skip().Take().AsEnumerable()</code> or <code>query.AsEnumerable().OrderBy().Skip().Take()</code>?</p>
    singulars
    1. This table or related slice is empty.
    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