转换 IQueryable<object> 时出现 NotSupportedException

NotSupportedException when converting an IQueryable<object>

当我这样做时:

    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

我想底层 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 返回的任何类型派生的class,那么您应该使用 OfType,而不是 Cast。

否则,Cast 可能会在 Where 之后,并被 Select 替换,后者显式创建 GroupOfBranches class 的实例。

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

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