我如何编写 EF.Functions 扩展方法?

我看到 EF Core 2 具有 EF.Functions 属性 EF Core 2.0 公告 EF Core 或提供者可以使用它来定义映射到数据库函数或运算符的方法,以便可以在 LINQ 查询中调用这些方法.它包括发送到数据库的 LIKE 方法.

I see that EF Core 2 has EF.Functions property EF Core 2.0 Announcement which can be used by EF Core or providers to define methods that map to database functions or operators so that those can be invoked in LINQ queries. It included LIKE method that gets sent to the database.

但我需要一个不同的方法,SOUNDEX(),它不被包括在内.我如何编写这样一个方法,将函数传递给数据库,就像 DbFunction 属性在 EF6 中所做的那样?或者我需要等待 MS 实施它?本质上,我需要生成类似

But I need a different method, SOUNDEX() that is not included. How do I write such a method that passes the function to the database the way DbFunction attribute did in EF6? Or I need to wait for MS to implement it? Essentially, I need to generate something like

SELECT * FROM Customer WHERE SOUNDEX(lastname) = SOUNDEX(@param)

推荐答案

EF.Functions 添加新的标量方法很容易 - 您只需在 DbFunctions 类上定义扩展方法.然而,提供 SQL 翻译很困难,需要深入研究 EFC 内部.

Adding new scalar method to EF.Functions is easy - you simply define extension method on DbFunctions class. However providing SQL translation is hard and requires digging into EFC internals.

然而,EFC 2.0 还引入了一种更简单的方法,在 EF Core 2.0 中的新功能 文档主题的数据库标量函数映射部分.

However EFC 2.0 also introduces a much simpler approach, explained in Database scalar function mapping section of the New features in EF Core 2.0 documentation topic.

据此,最简单的方法是向您的 DbContext 派生类添加一个静态方法,并使用 DbFunction 属性对其进行标记.例如

According to that, the easiest would be to add a static method to your DbContext derived class and mark it with DbFunction attribute. E.g.

public class MyDbContext : DbContext
{
    // ...

    [DbFunction("SOUNDEX")]
    public static string Soundex(string s) => throw new Exception();
}

并使用这样的东西:

string param = ...;
MyDbContext db = ...;
var query = db.Customers
    .Where(e => MyDbContext.Soundex(e.LastName) == MyDbContext.Soundex(param));

您可以在不同的类中声明此类静态方法,但是您需要使用 HasDbFunction fluent API 手动注册它们.

You can declare such static methods in a different class, but then you need to manually register them using HasDbFunction fluent API.

相关文章