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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With