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

编程入门 行业动态 更新时间:2024-10-12 01:26:23
本文介绍了如何编写EF.Functions扩展方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我看到EF Core 2具有EF.Functions属性 EF Core 2.0公告 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.它包含了将发送到数据库的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.

但是,"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(); }

并使用类似这样的内容:

and use something like this:

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.

更多推荐

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

本文发布于:2023-11-13 22:57:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1585554.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   EF   Functions

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!