OrderBy virtual property in entity structure

Is it possible to use orderby virtual properties for an object?

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 the TestName property, I get an error:

"The specified member of type 'TestName' is not supported in LINQ to Entities. Only initializers, entities, and property entities are supported."

Initially, I had a method in a partial class, the property is used to return data, but not for ordering.

Is there any way around this?

+5
source share
2 answers

Instead of .OrderBy(x => x.TestName) , you should instead use .ToList().OrderBy(x => x.TestName) in your EF request.

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

+3
source

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

https://github.com/hazzik/DelegateDecompiler

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

+1
source

Source: https://habr.com/ru/post/1265178/


All Articles