ArM*_*MaN 0 c# linq linq-to-entities entity-framework linq-to-sql
我有一个LINQ查询,想要选择我的实体类型,如下所示:
static void Main(string[] args)
{
using (var currentContext = new MyContext())
{
var x = (from c in currentContext.GeneralAccounts
select new { CType = c.GetType() }).ToList();
}
}
Run Code Online (Sandbox Code Playgroud)
但是这个查询会出错:
错误:LINQ to Entities无法识别方法'System.Type GetType()'方法,并且此方法无法转换为商店表达式.
你可以尝试这个:
var result = (from c in currentContext.GeneralAccounts
select c).AsEnumerable().Select(x=> new { CType = x.GetType() }).ToList();
Run Code Online (Sandbox Code Playgroud)
您收到错误是因为Linq表达式被转换为SQL,并且因为x.GetType()无法转换为SQL,因此您需要首先通过调用AsEnumerable来检索记录,然后获取其类型.
当您使用这样的查询时
from c in currentContext.GeneralAccounts
select new { CType = c.GetType() }
Run Code Online (Sandbox Code Playgroud)
然后,实体框架或LINQ-to-SQL将尝试从中形成SQL语句。但是对于某些事情,没有等效的SQL语句,在您的情况下,这就是GetType()问题所在。
您要做的是GetType()在客户端而不是数据库服务器上执行,因此您必须将查询更改为
// this can be translated into a SQL query
(from c in currentContext.GeneralAccounts
select c)
// turns the IQueryable into an IEnumerable, which means
// from now on LINQ-to-Objects is used
.AsEnumerable()
.Select(p => new { CType = p.GetType() })
.ToList()
Run Code Online (Sandbox Code Playgroud)