简体   繁体   English

OrderBy实体框架中的虚拟属性

[英]OrderBy virtual property in entity framework

Is it possible to orderby virtual properties on an entity? 是否可以通过实体的虚拟属性进行orderby

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: 当我通过TestName属性订购时,我收到错误:

"The specified type member 'TestName' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported." “LINQ to Entities不支持指定的类型成员'TestName'。仅支持初始化程序,实体成员和实体导航属性。”

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. 而不仅仅是.OrderBy(x => x.TestName)您必须在EF查询中使用.ToList().OrderBy(x => x.TestName)

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. 这是因为TestName属性不作为数据库表中的列存在,并且查询无法转换为SQL语句。 The .ToList() call will materialize the query into a C# collection which can then be ordered. .ToList()调用将查询实现为C#集合,然后可以对其进行排序。

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. 您可以使用DelegateDecompiler将属性内的代码扩展到表达式树,这意味着Linq to Entities可以从中生成SQL。

https://github.com/hazzik/DelegateDecompiler 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. 您只需要使用[Computed]属性.Decompile()属性,并调用.Decompile()作为linq查询的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM