blg*_*boy 5 c# entity-framework entity-framework-core
我有我一直在使用的扩展方法。直到最近,我才知道EF Core 2.x默认执行混合评估,这意味着对于它不知道如何转换为SQL的事情,它将从数据库中提取所有内容,然后执行内存中的LINQ查询。此后,我禁用了此行为。无论如何,这是我的扩展方法:
public static class RepositoryExtensions
{
public static IQueryable<T> NonDeleted<T>(this IQueryable<T> queryable) where T : IDeletable
{
return queryable.Where(x => !x.Deleted);
}
}
Run Code Online (Sandbox Code Playgroud)
然后,实体框架会引发异常,并带有以下消息(因为我此时已配置了它,而不是从数据库中获取所有内容并在本地进行评估):
警告“ Microsoft.EntityFrameworkCore.Query.QueryClientEvaluationWarning”生成的错误:LINQ表达式“其中Not(Convert([x],IDeletable).Deleted)”无法翻译,将在本地进行评估。通过将事件ID'RelationalEventId.QueryClientEvaluationWarning'传递到'DbContext.OnConfiguring'或'AddDbContext'中的'ConfigureWarnings'方法,可以抑制或记录此异常。
这种扩展方法在很多地方都在使用,所以我宁愿修复if并使它起作用(在数据库中评估),而不是去跨多个项目删除它,然后用代替.Where(x => !x.Deleted)
。
是否还有其他人遇到过这种情况,并且知道如何制作在数据库中评估的IQueryable扩展(在运行时转换为SQL)?在将LINQ转换为SQL时,似乎EF只是在查看具体的类?
更新:评论之一要求一个示例。做一些额外的测试,我可以看到这是应用于从EF Core返回的IQueryable时.FromSql
。如果.NonDeleted()
直接应用于实体Organization
,则似乎可以正常工作。
// Service layer
public class OrganizationService
{
public IEnumerable<Data.Entities.Organization> GetAllForUser(int? userId)
{
return _repository.GetOrganizationsByUserId(userId.GetValueOrDefault()).NonDeleted();
}
}
Run Code Online (Sandbox Code Playgroud)
//储存库层
using PrivateNameSpace.Common.EntityFramework;
using PrivateNameSpace.Data.DbContext;
using PrivateNameSpace.Data.Repos.Interfaces;
using Microsoft.EntityFrameworkCore;
using System.Data.SqlClient;
using System.Linq;
public class OrganizationRepository: Repository<Entities.Organization, int, OrganizationContext>, IOrganizationRepository
{
private const string storedProcedure = "dbo.sproc_organizations_by_userid";
public OrganizationRepository(OrganizationContext context) : base(context)
{
DbSet = Context.Organizations;
}
public IQueryable<Entities.Organization> GetOrganizationsByUserId(int userId)
{
var sql = $"{Sproc} @UserId";
var result = Context.Organizations.FromSql(sql, new SqlParameter("@UserId", userId));
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
虽然您可以使用其他查询表达式来编写原始 SQL 查询,例如
var searchTerm = ".NET";
var blogs = context.Blogs
.FromSql($"SELECT * FROM dbo.SearchBlogs({searchTerm})")
.Where(b => b.Rating > 3)
.OrderByDescending(b => b.Rating)
.ToList();
Run Code Online (Sandbox Code Playgroud)
如果原始 SQL 查询不是简单的 SELECT,则无法执行此操作。无论如何,您将始终过滤存储过程的结果,并且必须将过程结果加载到服务器上的临时表中,以便在服务器端应用其他查询运算符。这实施起来很复杂,而且价值不大。
归档时间: |
|
查看次数: |
181 次 |
最近记录: |