c# - Ef core 3 cast 无法翻译
问题描述
我想将我的 IQueryable 转换为这样的接口:
public static IQueryable<T> _enableFilter<T>(this IQueryable<T> queryable) => queryable.Where(x => (x as IEnable).Enable);
_newsRepository.BaseQuery.EnableFilter().FirstOrDefaultAsync(x => x.Id == model.Id);
它在 EF core 2.2 上的工作,但在 3 中我给出了这个错误:
System.InvalidOperationException : The LINQ expression 'Where<News>(
source: DbSet<News>,
predicate: (n) => (n as IEnable).Enable)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
解决方案
此查询在 EF Core 2.2 中也不起作用。这种转换在 SQL 中没有任何意义——SQL 中没有接口或继承。EF Core 3 之前有一个......不幸的功能,客户端评估。如果 EF Core 无法将某些内容转换为 SQL,它会将所有内容拉到客户端并尝试在那里过滤数据。不用说,这对性能来说是灾难性的。更糟糕的是,它在没有任何警告的情况下这样做了。警告或异常将使您能够识别并解决问题。至少,在 EF Core 2.2 中,可以禁用客户端评估。在 EF Core 3 中,这永远消失了。
至于方法本身,如果您使用类型约束,则根本不需要该转换,例如:
public static IQueryable<T> _enableFilter<T>(this IQueryable<T> queryable)
where T:IEnable
{
return queryable.Where(x => (x as IEnable).Enable);
}
我不确定 EF Core 会接受这一点 - 这是不寻常的语法。添加额外条件要容易得多,例如:
_newsRepository.BaseQuery.EnableFilter().FirstOrDefaultAsync(x => x.Id == model.Id && x.Enabled);
全局查询和软删除
如果您想对使用特定实体的所有查询应用过滤条件,例如实现软删除,您可以使用全局过滤器。事实上,软删除是文档中提到的第一个场景。
在您的上下文OnModelCreating()
方法中,您可以添加:
modelBuilder.Entity<SomeEntity>().HasQueryFilter(p => p.IsEnabled);
推荐阅读
- java - 为什么我的 Springboot 主方法在代码中只调用一次时启动 2 个线程?
- dafny - 是否存在将不变量更改为确保子句的一种解决方案?
- angular9 - 在新数据到来时创建要素后,我替换图层源但在地图上仍删除可见的要素(ArcGIS-js-api 4)
- python - 泡菜和追加的区别
- swagger - 如何让 JHipster 6.10 生成开放 api 3.0。代替或补充 Swagger 2 的文档
- ruby - 在 Ruby 中快速访问大型 CSV 文件中的各个行
- php - Eclipse IDE PHP 2020-06 测试服务器
- c# - 将多个刚体分配给功能
- java - 如何在java中打开csv文件时设置新密码
- typescript - 无法使用 Angular CLI 创建组件