gpt4 book ai didi

c# - 如何在 EF Core 中使用 DbFunction 翻译?

转载 作者:行者123 更新时间:2023-11-29 05:48:23 29 4
gpt4 key购买 nike

我正在寻找类似 EF.Functions.FreeText 的内容这是在 SQL Server 中实现的,但使用了 MATCH...AGAINST MySQL的语法。

这是我目前的工作流程:
AspNetCore 2.1.1
EntityFrameworkCore 2.1.4
Pomelo.EntityFrameworkCore.MySql 2.1.4

问题是 MySQL 使用两个函数,我不知道如何用 DbFunction 解释它并将每个参数分开。有谁知道如何实现这个?

这应该是 Linq 语法:

query.Where(x => DbContext.FullText(new[] { x.Col1, x.Col2, x.Col3 }, "keywords"));

这应该是SQL生成的结果:

SELECT * FROM t WHERE MATCH(`Col1`, `Col2`, `Col3`) AGAINST('keywords');

我正在尝试使用 HasTranslation 来遵循以下示例功能: https://github.com/aspnet/EntityFrameworkCore/issues/11295#issuecomment-511440395 https://github.com/aspnet/EntityFrameworkCore/issues/10241#issuecomment-342989770

注意:我知道可以用 FromSql 解决,但这不是我要找的。

最佳答案

当我需要时,你的用例与我的非常相似 ROW_NUMBER EF Core 中的支持。

例子:

// gets translated to
// ROW_NUMBER() OVER(PARTITION BY ProductId ORDER BY OrderId, Count)
DbContext.OrderItems.Select(o => new {
RowNumber = EF.Functions.RowNumber(o.ProductId, new {
o.OrderId,
o.Count
})
})

使用匿名类代替数组

您要做的第一件事是从使用数组切换到匿名类,即您将调用从

DbContext.FullText(new[] { x.Col1, x.Col2, x.Col3 }, "keywords")

DbContext.FullText(new { x.Col1, x.Col2, x.Col3 }, "keywords")

参数的排序顺序将保持在查询中定义的顺序,即new { x.Col1, x.Col2 }将被翻译成Col1, Col2new { x.Col2, x.Col1 }Col2, Col1 .

您甚至可以访问以下内容:new { x.Col1, _ = x.Col1, Foo = "bar" }那将被翻译成Col1, Col1, 'bar' .

实现自定义 IMethodCallTranslator

如果您需要一些提示,那么您可以在 Azure DevOps: RowNumber Support 上查看我的代码或者,如果您可以等待几天,那么我会提供一篇关于自定义函数实现的博文。

更新(2019 年 7 月 31 日)

博客文章:

更新(2019 年 7 月 27 日)

感谢下面的评论,我发现需要进行一些说明。

1) 正如下面评论中指出的,还有另一种方法。与 HasDbFunction我可以节省一些打字时间,例如使用 EF 注册翻译器的代码,但我仍然需要 RowNumberExpression因为该函数有 2 组参数(用于 PARTITION BYORDER BY )和现有的 SqlFunctionExpression不支持那个。 (或者我错过了什么?)我选择 IMethodCallTranslator 方法的原因是因为我希望在设置 DbContextOptionsBuilder 期间完成此功能的配置而不是 OnModelCreating .也就是说,这是我个人的喜好。

最后线程创建者可以使用HasDbFunction也可以实现所需的功能。在我的例子中,代码如下所示:

// OnModelCreating
var methodInfo = typeof(DemoDbContext).GetMethod(nameof(DemoRowNumber));

modelBuilder.HasDbFunction(methodInfo)
.HasTranslation(expressions => {
var partitionBy = (Expression[])((ConstantExpression)expressions.First()).Value;
var orderBy = (Expression[])((ConstantExpression)expressions.Skip(1).First()).Value;

return new RowNumberExpression(partitionBy, orderBy);
});

// the usage with this approach is identical to my current approach
.Select(c => new {
RowNumber = DemoDbContext.DemoRowNumber(
new { c.Id },
new { c.RowVersion })
})

2) 匿名类型不能强制其成员的类型,因此如果使用 integer 调用函数,您可能会得到运行时异常。而不是 string .尽管如此,它仍然是有效的解决方案。根据您所服务的客户,解决方案的可行性可能或多或少,最终决定权在客户。不提供任何替代方案也是一种可能的解决方案,但不是令人满意的解决方案。特别是,如果不需要使用 SQL(因为编译器对你的支持更少),那么运行时异常可能是一个很好的妥协。

但是,如果妥协仍然不能接受,那么我们可以研究如何添加对数组的支持。第一种方法可能是实现自定义 IExpressionFragmentTranslator将数组的处理“重定向”给我们。

Please note, it is just a prototype and needs more investigation/testing :-)

// to get into EF pipeline
public class DemoArrayTranslator : IExpressionFragmentTranslator
{
public Expression Translate(Expression expression)
{
if (expression?.NodeType == ExpressionType.NewArrayInit)
{
var arrayInit = (NewArrayExpression)expression;
return new DemoArrayInitExpression(arrayInit.Type, arrayInit.Expressions);
}

return null;
}
}

// lets visitors visit the array-elements
public class DemoArrayInitExpression : Expression
{
private readonly ReadOnlyCollection<Expression> _expressions;

public override Type Type { get; }
public override ExpressionType NodeType => ExpressionType.Extension;

public DemoArrayInitExpression(Type type,
ReadOnlyCollection<Expression> expressions)
{
Type = type ?? throw new ArgumentNullException(nameof(type));
_expressions = expressions ?? throw new ArgumentNullException(nameof(expressions));
}

protected override Expression Accept(ExpressionVisitor visitor)
{
var visitedExpression = visitor.Visit(_expressions);
return NewArrayInit(Type.GetElementType(), visitedExpression);
}
}

// adds our DemoArrayTranslator to the others
public class DemoRelationalCompositeExpressionFragmentTranslator
: RelationalCompositeExpressionFragmentTranslator
{
public DemoRelationalCompositeExpressionFragmentTranslator(
RelationalCompositeExpressionFragmentTranslatorDependencies dependencies)
: base(dependencies)
{
AddTranslators(new[] { new DemoArrayTranslator() });
}
}

// Register the translator
services
.AddDbContext<DemoDbContext>(builder => builder
.ReplaceService<IExpressionFragmentTranslator,
DemoRelationalCompositeExpressionFragmentTranslator>());

为了测试,我引入了另一个包含 Guid[] 的重载作为参数。尽管如此,这种方法在我的用例中根本没有意义:)

public static long RowNumber(this DbFunctions _, Guid[] orderBy) 

并调整了方法的使用

// Translates to ROW_NUMBER() OVER(ORDER BY Id)
.Select(c => new {
RowNumber = EF.Functions.RowNumber(new Guid[] { c.Id })
})

关于c# - 如何在 EF Core 中使用 DbFunction 翻译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57206717/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com