【问题标题】:NotSupportedException when converting an IQueryable<object>转换 IQueryable<object> 时出现 NotSupportedException
【发布时间】:2016-06-30 12:10:37
【问题描述】:

当我这样做时:

    var db = new NotentoolEntities();
    IQueryable<GroupOfBranches> queryGOB = db.tabGroupOfBranches.Cast<GroupOfBranches>().Where(x => x.intGroupID.Equals(ID));
    List<GroupOfBranches> GOB = new List<GroupOfBranches>(queryGOB); //here is the error

我遇到以下错误:

A first chance exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll

【问题讨论】:

  • entityframework 不支持的 Equals 函数可能存在问题..
  • Where() 之后调用ToList() 可能更清楚
  • 我的错误在第三行,但我也尝试替换 Equals 并得到同样的错误
  • 你为什么要投到 GroupOfBranches?
  • 因为我需要返回这个对象

标签: c# linq exception iqueryable


【解决方案1】:

我认为底层 LINQ 提供程序无法将对 Equals 的调用转换为它所知道的任何内容。

请改用 == 运算符。这将最终形成一个不同的表达式树,可以翻译。

var db = new NotentoolEntities();
IQueryable<GroupOfBranches> queryGOB =
    db.tabGroupOfBranches.Cast<GroupOfBranches>().Where(x => x.intGroupID == ID));
List<GroupOfBranches> GOB = new List<GroupOfBranches>(queryGOB);

如果 GroupOfBranches 派生自 tabGroupOfBranches 返回的任何类型,那么您可能应该使用 OfType,而不是 Cast。

否则,Cast 可能会跟随 Where,并被替换为 Select,后者显式创建 GroupOfBranches 类的实例。

【讨论】:

  • 还会发生吗?那是执行查询的地方,我希望看到第三行中出现的错误。
  • 是的,它仍然会发生
  • 尝试执行 queryGOB.ToList() 而不执行任何其他操作。这将限制选项。
  • 你有堆栈跟踪吗?异常究竟是在哪个方法中发生的?
  • 我已经用关于 Cast 的建议更新了答案。如果不是在哪里,那么就是演员阵容失败了。
【解决方案2】:

可能会考虑将您的代码更改为

using (var db = new NotentoolEntities())
   {
      var GOB = db.tabGroupOfBranches.Where(x => x.intGroupID == ID).Select(y => new GroupOfBranches
          {
              /// here specify your fields
          }).AsNoTracking().ToList();
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-06
    • 1970-01-01
    • 2014-01-21
    • 1970-01-01
    • 2014-07-22
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    相关资源
    最近更新 更多