DbContext.Query <t>()上的EF Core 2.1 InvalidCastException

时间:2018-09-07 14:17:54

标签: ef-core-2.1

给出:

public class MyClass
{
  public MyClass(ApplicationDbContext db)
  {
     var query = db.Query<IdentityUser>();
  }
}

使用ASP.NET Core 2.1,我在db.Query<IdentityUser>()调用中收到此异常:

System.InvalidCastException: 'Unable to cast object of type 'Microsoft.EntityFrameworkCore.Internal.InternalDbSet\`1[Microsoft.AspNetCore.Identity.IdentityUser]' to type 'Microsoft.EntityFrameworkCore.DbQuery\`1[Microsoft.AspNetCore.Identity.IdentityUser]'.'

我遇到了自己的实体,并使用罐头ApplicationDbContext / IdentityUser以最少的代码复制了它。这是.NET Core 2.1中的错误还是我做错了什么?

这是githubDbContext.Query<T>()的源代码:

public virtual DbQuery<TQuery> Query<TQuery>()
            where TQuery : class
            => (DbQuery<TQuery>)((IDbQueryCache)this)
                .GetOrAddQuery(DbContextDependencies.QuerySource, typeof(TQuery));

似乎引发了将((IDbQueryCache)this).GetOrAddQuery(DbContextDependencies.QuerySource, typeof(TQuery))强制转换为(DbQuery<TQuery>)的异常

我在github上打开了一个issue,因为从我所知这似乎是一个错误。

1 个答案:

答案 0 :(得分:0)

我在github上发表的评论中有解决方法:

  

您不能为EntityTypes调用Query<>方法。您必须使用Set<>   方法。

如果可能的话,TQuery比仅仅class受到更多约束可能会有所帮助。

相关问题