问题
I'm trying to implement a custom IMethodCallTranslator
in EF Core 3.1 with the Sqlite provider.
I have created:
- An extension method off of
this DbFunctions
which is called at query time - An implementation of
IMethodCallTranslator
which isTranslate
not called - A derived
RelationalMethodCallTranslatorProvider
which I'm passing an instance of myIMethodCallTranslator
. This constructor is hit. I also tried overridingRelationalMethodCallTranslatorProvider.Translate
and this was not hit. - An implementation of
IDbContextOptionsExtension
(and its info class) which registers theRelationalMethodCallTranslatorProvider
as a singletonIMethodCallTranslatorProvider
.
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