我在如何将Linq where子句转换为Sql时遇到问题。
我正在使用EnumToStringConverter
将实体enum
的属性映射到文本db列。只需从DbContext查询我的实体,一切都可以正常工作。
然后我开始使用LinqKit和Expressions具有可重用的过滤器。我创建了一个表达式,该表达式接受我的实体并通过对该实体其他属性的一些计算得出我的枚举。我会尝试用代码来解释自己,因为单词使我不满意。 我将写一个示例,这样我就不必发布完整的代码,但是逻辑将是相同的。您可以找到一个包含项目的GitHub存储库,以在此处复制问题:https://github.com/pinoy4/efcore-enum-to-string-test
模型类:
public class MyEntity
{
public Guid Id { get; set; }
public MyEnum Status { get; set; }
public DateTime DueAtDate { get; set; }
}
public MyEnum
{
New = 0,
InProgress = 1,
Overdue = 2
}
FluentAPI配置
public class MyEntityConfiguration : IEntityTypeConfiguration<MyEntity>
{
public void Configure(EntityTypeBuilder<MyEntity> builder)
{
// irrelevant parts of configuration skipped here
builder.Property(e => e.Status)
.HasColumnName("status")
.IsRequired()
.HasConversion(new EnumToStringConverter<MyEnum>());
}
}
Linq表达式是使用静态方法生成的。有两个:
public static class MyExpressions
{
public static Expression<Func<MyEntity, MyEnum>> CalculateStatus(DateTime now)
{
/*
* This is the tricky part as in one case I am returning
* an enum value that am am setting here and in the other
* case it is an enum value that is taken from the entity.
*/
return e => e.DueAtDate < now ? MyEnum.Overdue : e.Status;
}
public static Expression<Func<MyEntity, bool>> GetOverdue(DateTime now)
{
var calculatedStatus = CalculateStatus(now);
return e => calculatedStatus.Invoke(e) == MyEnum.Overdue;
}
}
现在我们有了上面的代码,我这样编写查询:
var getOverdueFilter = MyExpressions.GetOverdue(DateTime.UtcNow);
DbContext.MyEntities.AsExpandable().Where(getOverdueFilter).ToList();
这被翻译成以下SQL:
SELECT ... WHERE CASE
WHEN e.due_at_date < $2 /* the date that we are passing as a parameter */
THEN 2 ELSE e.status
END = 2;
问题是CASE
语句正在将'Overdue'
(使用EnumToStringConverter
正确翻译的语句)与给出int
的表达式进行比较(2是值(对于MyEnum.Overdue情况)为true,为string
(例如状态)为false。这显然是无效的SQL。
我真的不知道该如何解决。有帮助吗?
答案 0 :(得分:3)
问题与LinqKit无关,而是表达式本身,特别是条件运算符和当前的EF Core 2查询转换和值转换。
问题在于,当前值转换是按属性(列)而不是按类型指定的。因此,为了正确地转换为SQL,转换器必须从属性“推断”常量/参数类型。它适用于大多数类型的表达式,但不适用于条件运算符。
因此,您应该做的第一件事就是将其报告给EF Core问题跟踪器。
关于解决方法:
不幸的是,该功能位于称为DefaultQuerySqlGenerator
的基础结构类中,该基础结构类由每个数据库提供程序继承。可以替换该类提供的服务,尽管可以用一些复杂的方法来替换,这可以从我对Ef-Core - What regex can I use to replace table names with nolock ones in Db Interceptor的回答中看出,并且还必须对要支持的每个数据库提供程序都进行此操作。
对于SqlServer,它需要类似以下内容(经过测试):
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore.Query.Expressions;
using Microsoft.EntityFrameworkCore.Query.Sql;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.SqlServer.Infrastructure.Internal;
using Microsoft.EntityFrameworkCore.SqlServer.Query.Sql.Internal;
namespace Microsoft.EntityFrameworkCore
{
public static partial class CustomDbContextOptionsBuilderExtensions
{
public static DbContextOptionsBuilder UseCustomSqlServerQuerySqlGenerator(this DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.ReplaceService<IQuerySqlGeneratorFactory, CustomSqlServerQuerySqlGeneratorFactory>();
return optionsBuilder;
}
}
}
namespace Microsoft.EntityFrameworkCore.SqlServer.Query.Sql.Internal
{
class CustomSqlServerQuerySqlGeneratorFactory : SqlServerQuerySqlGeneratorFactory
{
private readonly ISqlServerOptions sqlServerOptions;
public CustomSqlServerQuerySqlGeneratorFactory(QuerySqlGeneratorDependencies dependencies, ISqlServerOptions sqlServerOptions)
: base(dependencies, sqlServerOptions) => this.sqlServerOptions = sqlServerOptions;
public override IQuerySqlGenerator CreateDefault(SelectExpression selectExpression) =>
new CustomSqlServerQuerySqlGenerator(Dependencies, selectExpression, sqlServerOptions.RowNumberPagingEnabled);
}
public class CustomSqlServerQuerySqlGenerator : SqlServerQuerySqlGenerator
{
public CustomSqlServerQuerySqlGenerator(QuerySqlGeneratorDependencies dependencies, SelectExpression selectExpression, bool rowNumberPagingEnabled)
: base(dependencies, selectExpression, rowNumberPagingEnabled) { }
protected override RelationalTypeMapping InferTypeMappingFromColumn(Expression expression)
{
if (expression is UnaryExpression unaryExpression)
return InferTypeMappingFromColumn(unaryExpression.Operand);
if (expression is ConditionalExpression conditionalExpression)
return InferTypeMappingFromColumn(conditionalExpression.IfTrue) ?? InferTypeMappingFromColumn(conditionalExpression.IfFalse);
return base.InferTypeMappingFromColumn(expression);
}
}
}
以及PostgreSQL(未测试):
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore.Query.Expressions;
using Microsoft.EntityFrameworkCore.Query.Sql;
using Microsoft.EntityFrameworkCore.Storage;
using Npgsql.EntityFrameworkCore.PostgreSQL.Infrastructure.Internal;
using Npgsql.EntityFrameworkCore.PostgreSQL.Query.Sql.Internal;
namespace Microsoft.EntityFrameworkCore
{
public static partial class CustomDbContextOptionsBuilderExtensions
{
public static DbContextOptionsBuilder UseCustomNpgsqlQuerySqlGenerator(this DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.ReplaceService<IQuerySqlGeneratorFactory, CustomNpgsqlQuerySqlGeneratorFactory>();
return optionsBuilder;
}
}
}
namespace Npgsql.EntityFrameworkCore.PostgreSQL.Query.Sql.Internal
{
class CustomNpgsqlQuerySqlGeneratorFactory : NpgsqlQuerySqlGeneratorFactory
{
private readonly INpgsqlOptions npgsqlOptions;
public CustomNpgsqlQuerySqlGeneratorFactory(QuerySqlGeneratorDependencies dependencies, INpgsqlOptions npgsqlOptions)
: base(dependencies, npgsqlOptions) => this.npgsqlOptions = npgsqlOptions;
public override IQuerySqlGenerator CreateDefault(SelectExpression selectExpression) =>
new CustomNpgsqlQuerySqlGenerator(Dependencies, selectExpression, npgsqlOptions.ReverseNullOrderingEnabled);
}
public class CustomNpgsqlQuerySqlGenerator : NpgsqlQuerySqlGenerator
{
public CustomNpgsqlQuerySqlGenerator(QuerySqlGeneratorDependencies dependencies, SelectExpression selectExpression, bool reverseNullOrderingEnabled)
: base(dependencies, selectExpression, reverseNullOrderingEnabled) { }
protected override RelationalTypeMapping InferTypeMappingFromColumn(Expression expression)
{
if (expression is UnaryExpression unaryExpression)
return InferTypeMappingFromColumn(unaryExpression.Operand);
if (expression is ConditionalExpression conditionalExpression)
return InferTypeMappingFromColumn(conditionalExpression.IfTrue) ?? InferTypeMappingFromColumn(conditionalExpression.IfFalse);
return base.InferTypeMappingFromColumn(expression);
}
}
}
除了样板代码之外,解决方法是
if (expression is UnaryExpression unaryExpression)
return InferTypeMappingFromColumn(unaryExpression.Operand);
if (expression is ConditionalExpression conditionalExpression)
return InferTypeMappingFromColumn(conditionalExpression.IfTrue) ?? InferTypeMappingFromColumn(conditionalExpression.IfFalse);
内部InferTypeMappingFromColumn
方法覆盖。
为了生效,您需要在使用UseCustom{Database}QuerySqlGenerator
的任何地方添加Use{Database}
,例如
.UseSqlServer(...)
.UseCustomSqlServerQuerySqlGenerator()
或
.UseNpgsql(...)
.UseCustomNpgsqlQuerySqlGenerator()
等
完成此操作后,翻译(至少对于SqlServer)是预期的:
WHERE CASE
WHEN [e].[DueAtDate] < @__now_0
THEN 'Overdue' ELSE [e].[Status]
END = 'Overdue'