Search code examples
entity-framework-coreef-core-3.0ef-core-3.1

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


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.


Solution

  • 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) });