【问题标题】:GetType Of Entity in LINQ Query在 LINQ 查询中获取实体的类型
【发布时间】:2014-08-12 08:52:45
【问题描述】:

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

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

但是这个查询出错了:

错误:LINQ to Entities 无法识别方法“System.Type GetType()”方法,并且该方法无法转换为存储表达式。

【问题讨论】:

    标签: c# linq entity-framework linq-to-sql linq-to-entities


    【解决方案1】:

    你可以试试这个:

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

    您收到错误是因为 Linq 表达式被翻译成 SQL,并且由于 x.GetType() 无法翻译成 SQL,因此您需要先通过调用 AsEnumerable 来检索记录,然后再获取其类型。

    【讨论】:

    • @AsifMushtaq 我忘了在AsEnumerable 后面加上()。我想这就是原因。然而,有些人的经典行为是这样的,他们毫无理由地投反对票。当然,这很有帮助。
    • 但这应该没什么大不了的。 :)
    • @AsifMushtaq 我知道...但是我们能做些什么呢?我们必须和他们一起离开。
    【解决方案2】:

    当你使用这样的查询时

    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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-23
      • 1970-01-01
      相关资源
      最近更新 更多