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?
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.