What is required for EF Core's IMethodCallTranslator to work with `EF.Functions` to provide a custom function?

天涯浪子 提交于 2021-01-29 13:28:59

问题


I'm trying to implement a custom IMethodCallTranslator in EF Core 3.1 with the Sqlite provider.

I have created:

  1. An extension method off of this DbFunctions which is called at query time
  2. An implementation of IMethodCallTranslator which is Translate not called
  3. A derived RelationalMethodCallTranslatorProvider which I'm passing an instance of my IMethodCallTranslator. This constructor is hit. I also tried overriding RelationalMethodCallTranslatorProvider.Translate and this was not hit.
  4. An implementation of IDbContextOptionsExtension (and its info class) which registers the RelationalMethodCallTranslatorProvider as a singleton IMethodCallTranslatorProvider.

All of this is added via OnConfiguring by getting the IDbContextOptionsBuilderInfrastructure form of the options.

Am I missing something? I've tried following: https://github.com/tkhadimullin/ef-core-custom-functions/tree/feature/ef-3.1-version in my code, yet it's invoking the extension method, not my translator.


回答1:


Apparently, you can't pass a reference to your full entity class to the function for further processing:

Doesn't work:

public static string DoWork(this DbFunctions _, object entity, string key)
//...
dbContext.Items.Select(i => new { Entity = i, String = EF.Functions.DoWork(i, i.StringValue) });

Where this will:

public static string DoWork(this DbFunctions _, string key)
//...
dbContext.Items.Select(i => new { Entity = i, String = EF.Functions.DoWork(i.StringValue) });

Also, generics are supported so it would be a nice way to introspect call and get the type of the entity for the model in a RelationalMethodCallTranslatorProvider.

public static string DoWork<T>(this DbFunctions _, string key)
//...
dbContext.Items.Select(i => new { Entity = i, String = EF.Functions.DoWork<Item>(i.StringValue) });


来源:https://stackoverflow.com/questions/61047557/what-is-required-for-ef-cores-imethodcalltranslator-to-work-with-ef-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!