获取LINQ查询中实体的类型

本文关键字:类型 实体 LINQ 查询 获取 | 更新日期: 2023-09-27 18:17:40

我有一个LINQ查询,想要选择我的实体的类型,像这样:

    static void Main(string[] args)
    {
        using (var currentContext = new MyContext())
        {
            var x = (from c in currentContext.GeneralAccounts
                    select new  { CType = c.GetType() }).ToList();
        }
    }

但是这个查询出错了:

ERROR: LINQ to Entities不识别方法System。键入GetType()'方法,此方法不能转换为存储表达式

获取LINQ查询中实体的类型

你可以试试这个:

var result  = (from c in currentContext.GeneralAccounts
               select c).AsEnumerable().Select(x=> new  { CType = x.GetType() }).ToList();

你得到的错误,因为Linq表达式被翻译成SQL,因为x.GetType()不能被翻译成SQL,因此你需要通过调用AsEnumerable首先检索记录,然后得到它的类型。

当您使用这样的查询时

from c in currentContext.GeneralAccounts
select new  { CType = c.GetType() }

则实体框架,或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()