Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OrderBy virtual property in entity framework

Is it possible to orderby virtual properties on an entity?

I have a class similar to:

public int Id{get;set;}
public string Name {get;set;}

public virtual string TestName
{
   get { return string.Format("{0}{1}", Name , Id); }
}

When i order by the TestName property, i get the error:

"The specified type member 'TestName' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported."

I originally had the method in a partial class, the property is used in returning data but not ordering.

Is there a way around this?

like image 707
Sam Jones Avatar asked Oct 17 '22 16:10

Sam Jones


2 Answers

Instead of just .OrderBy(x => x.TestName) you must instead use .ToList().OrderBy(x => x.TestName) on your EF query.

This is because the TestName property does not exist as a column in the database table and the query cannot be converted to a SQL statement. The .ToList() call will materialize the query into a C# collection which can then be ordered.

like image 86
Mark E Avatar answered Oct 20 '22 10:10

Mark E


You can use DelegateDecompiler to expand the code inside a property to an expression tree, which means Linq to Entities can generate SQL from it.

https://github.com/hazzik/DelegateDecompiler

You simply need to decorate the property with the [Computed] attribute, and call .Decompile() as part of the linq query.

like image 20
Jonas Høgh Avatar answered Oct 20 '22 11:10

Jonas Høgh