本文主要是講解EF Core3.0+ 如何實現自定義的數據庫擴展函數html
雖然EF.Functions 提供了不少數據庫函數,可是並不全面.好比加密解密..數據庫
這樣的話 咱們就須要本身擴展這些數據庫函數 從而達到調用的目的.express
本文以達夢數據庫爲例(其餘數據庫都同樣)..框架
上篇文章推薦:ide
EF Core3.0+ 經過攔截器實現讀寫分離與SQL日誌記錄函數
首先咱們須要建立自定義的擴展方法以下:post
public static class DbFunctionsExtensions { /// <summary> /// 調用數據庫的加密方法 /// </summary> /// <param name="_"></param> /// <param name="context"></param> /// <param name="typeid"></param> /// <param name="key"></param> /// <returns></returns> public static string DmAlgorithmsEncrypt(this DbFunctions _, string context, int typeid, string key) { throw new InvalidOperationException( "該方法僅用於實體框架核心,沒有內存實現。"); } /// <summary> /// 調用數據庫的解密方法 /// </summary> /// <param name="_"></param> /// <param name="context"></param> /// <param name="typeid"></param> /// <param name="key"></param> /// <returns></returns> public static string DmAlgorithmsDecrypt(this DbFunctions _, string context, int typeid, string key) { throw new InvalidOperationException( "該方法僅用於實體框架核心,沒有內存實現。"); }
很簡單,咱們只須要定義2個靜態擴展方法,而且拋出一個InvalidOperationException異常便可.測試
這裏記住IMethodCallTranslator這個接口,咱們須要實現它,以下:ui
public class DmDbFunctionsTranslateImpl : IMethodCallTranslator { private readonly ISqlExpressionFactory _expressionFactory; private static readonly MethodInfo _dmAlgorithmsEncryptMethod = typeof(DbFunctionsExtensions).GetMethod( nameof(DbFunctionsExtensions.DmAlgorithmsEncrypt), new[] { typeof(DbFunctions), typeof(string), typeof(int), typeof(string) }); private static readonly MethodInfo _dmAlgorithmsDecryptMethod = typeof(DbFunctionsExtensions).GetMethod( nameof(DbFunctionsExtensions.DmAlgorithmsDecrypt), new[] { typeof(DbFunctions), typeof(string), typeof(int), typeof(string) }); public DmDbFunctionsTranslateImpl(ISqlExpressionFactory expressionFactory) { _expressionFactory = expressionFactory; } public SqlExpression Translate(SqlExpression instance, MethodInfo method, IReadOnlyList<SqlExpression> arguments) { //判斷方法是否一致 if (method == _dmAlgorithmsEncryptMethod) { var args = new List<SqlExpression> { arguments[1], arguments[2], arguments[3] }; return _expressionFactory.Function(instance, "CFALGORITHMSENCRYPT", args, typeof(string)); } if (method == _dmAlgorithmsDecryptMethod) { var args = new List<SqlExpression> { arguments[1], arguments[2], arguments[3] }; return _expressionFactory.Function(instance, "CFALGORITHMSDECRYPT", args, typeof(string)); } return null; } }
public sealed class DmAlgorithmsMethodCallTranslatorPlugin : RelationalMethodCallTranslatorProvider { public DmAlgorithmsMethodCallTranslatorPlugin(RelationalMethodCallTranslatorProviderDependencies dependencies) : base(dependencies) { ISqlExpressionFactory expressionFactory = dependencies.SqlExpressionFactory; AddTranslators( new IMethodCallTranslator[] { //這裏,將剛剛的方法轉換器添加到擴展 new DmDbFunctionsTranslateImpl(expressionFactory) }); } }
這個類主要是將咱們剛剛建立的方法轉換器添加SQL表達式工廠(SqlExpressionFactory)當中.this
代碼以下,關鍵點加了註釋,自行參考..
public class DmDbContextOptionsExtension : IDbContextOptionsExtension { private DbContextOptionsExtensionInfo _info; public void Validate(IDbContextOptions options) { } public DbContextOptionsExtensionInfo Info { get { return this._info ??= new MyDbContextOptionsExtensionInfo(this); } } void IDbContextOptionsExtension.ApplyServices(IServiceCollection services) { //這裏將轉換器注入到服務當中. services.AddSingleton<IMethodCallTranslatorProvider, DmAlgorithmsMethodCallTranslatorPlugin>(); } private sealed class MyDbContextOptionsExtensionInfo : DbContextOptionsExtensionInfo { public MyDbContextOptionsExtensionInfo(IDbContextOptionsExtension instance) : base(instance) { } public override bool IsDatabaseProvider => false; public override string LogFragment => ""; public override void PopulateDebugInfo(IDictionary<string, string> debugInfo) { } public override long GetServiceProviderHashCode() { return 0; } } }
public static class DmDbContextOptionsBuilderExtensions { public static DbContextOptionsBuilder UseDmAlgorithmsEncryptionFunctions( this DbContextOptionsBuilder optionsBuilder) { //將自定義的配置類添加到配置選項中 var extension = GetOrCreateExtension(optionsBuilder); ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension); return optionsBuilder; } //生成建立擴展類 private static DmDbContextOptionsExtension GetOrCreateExtension(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.Options.FindExtension<DmDbContextOptionsExtension>() ?? new DmDbContextOptionsExtension(); }
咱們先在數據庫插入一條加密數據以下:
insert into "tab"."tab"( "XingMing", "ZhengJianHao", "ShouJiHao") VALUES( '測試數據1', CFALGORITHMSENCRYPT('123456789',514,'ABC'),'77777');
而後咱們編寫查詢代碼:
var ddd= Context.Where(a => EF.Functions.DmAlgorithmsDecrypt(a.ZhengJianHao, 514, "ABC") == "123456789").First();
這裏,咱們將數據解密後在對比
查詢效果以下:
咱們經過監控SQL語句 能夠看到以下SQL語句:
這裏,已經將咱們的自定義擴展函數轉換成了SQL函數 並在數據庫執行了.
這裏咱們就完成了整個SQL函數的擴展. 寫這篇主要是爲了拋磚引玉..
目前這種擴展方式,在查詢的時候 能夠正常的生成SQL語句,
可是在ADD 和Update的時候 並不會生成對應的語句,因此想問問各位大佬,有沒有更好的實現方式.