Skip to content

Value Converters: Enable passing in some context #12205

Description

@HaoK

Needed to enable: https://github.com/aspnet/Identity/issues/1753

Today value converters are only given the value, it would be nice to be able to flow context, so like in the identity case, we would be able to flow the entire user entity.

cc @blowdart this potentially would help for your non stable encryption as well right?

Activity

  1. blowdart commented on Jun 1, 2018

    @blowdart

    It'd make it better to make decisions on yes, at the core (pun intended) I'd like to know what the field is that I'm about to play with.

  2. HaoK commented on Jun 1, 2018

    @HaoK
    MemberAuthor

    So maybe Convert(value, user, "property")?

  3. self-assigned this
    on Jun 1, 2018
  4. added this to the 3.0.0 milestone on Jun 1, 2018
  5. ajcvickers commented on Apr 25, 2019

    @ajcvickers
    Contributor

    Consider also here the case where conversion needs to call some async method.

  6. divega commented on Apr 25, 2019

    @divega
    Contributor

    I wonder if enabling async conversions would open a pit of failure. These conversions tend to be very granular, and this would introduce latency for each of them.

  7. roji commented on Apr 26, 2019

    @roji
    Member

    @divega there's a possible scenario where you'd only occasionally need to do I/O, i.e. to fetch the new key or whatever, so 99% of invocations would return synchronously. That's a bit like how my mental model currently looks like for SQL Server access tokens.

    But it's true there's a danger of a pit of failure where hapless users start doing networking on each and every value read/write.

  8. ajcvickers commented on Apr 26, 2019

    @ajcvickers
    Contributor

    @divega @roji Agreed that allowing value converters to do async is likely a pit of failure. My intention was not to imply we should do this, but rather that we should consider the scenario and see if we can come up with something that makes sense in this kind of case. At the moment I don't have any great ideas, so really for now this is just something to think about when I get to working on this.

  9. StevenRasmussen commented on Apr 26, 2019

    @StevenRasmussen

    @divega @roji @ajcvickers - as a user of EF Core and and a heavy believer in async I would love to have this option. For sure there is a potential to kill an app if you are doing any sort of heavy lifting or IO operations but I do still think that there is value in providing this as an option. The potential for doing IO and heavy operations still exist in the synchronous version, it's maybe less in-your-face in an async operation and thus maybe some of the hesitation here. Maybe just adding a warning would suffice when using the async version? Anyway, just my 2 cents ;)

  10. roji commented on Apr 26, 2019

    @roji
    Member

    @StevenRasmussen do you have a specific scenario in mind that this would enable?

  11. StevenRasmussen commented on Apr 26, 2019

    @StevenRasmussen

    @roji - I could potentially see a scenario where a setting or some other type of configuration would need to be retrieved in order to determine how something might be converted. This information might be in a file, DB or retrieved from an endpoint. This would ideally use an async API method call but then cache the result so that further calls to retrieve this information would not take the IO hit. So the responsibility to make the async call performant (by caching or other methods) is on the developer but it would be nice not to have to use the synchronous versions of existing API calls, or in some instances supply a custom synchronous version just for this purpose.

  12. 17 remaining items

  13. soroshsabz commented on Mar 13, 2024

    @soroshsabz

    ITNOA

    Hi,

    How many votes needed to start implementation of this feature?

  14. ajcvickers commented on Mar 13, 2024

    @ajcvickers
    Contributor

    @soroshsabz There isn't a fixed number. The more votes there are, the higher the priority going into the planning process. Currently, about 80 votes are needed to get into the top 25 issues.

  15. Misiu commented on Jul 1, 2024

    @Misiu

    As of today, there are 103 votes.

  16. Li7ye commented on Jul 20, 2024

    @Li7ye

    Because of this feature is not coming. I share to my workaround for everyone. You can download Demo code for you reference. Only can support non-async scenario and it just a demo not a fully verified solution.

    The challenge is that value converter expression tree only can reference a constant object.
    e.g. Expression<Fun<string,string>> exp = value=> dbContext.Conveter(value). Only a dbContext instance is cached in expression tree by closure. So, the dbContext can be as a singleton and can't represent the current dbContext in later.

    To solve this problem, using AsycLocal<DbContext> to save dbContext instance in the current thread. Despite, it is a singleton but it can represent the current dbContext as long as can set AsycLocal<DbContext> value before any operation. e.g. in DbContext constructor.

    AsyncLocalCurrentDbContext is DbContext wrapper class.

    internal class AsyncLocalCurrentDbContext
    {
        private readonly AsyncLocal<DbContext> asyncLocal= new();
    
        public DbContext Current
        {
            get => asyncLocal.Value!;
            set => asyncLocal.Value = value;
        }
    }
    
    //register in EF Core DI container.
    svcs.AddSingleton<AsyncLocalCurrentDbContext>()

    In addition, must set AsyncLocalCurrentDbContext value at IDbSetInitializer.InitializeSets() timing. Because IDbSetInitializer.InitializeSets() is executed in DbContext constructor.

    internal class InitializeAsycLocalCurrentDbContext(AsyncLocalCurrentDbContext currentDbContext, IDbSetInitializer innerlDbSetInitializer) : IDbSetInitializer
    {
        public void InitializeSets(DbContext context)
        {
            innerlDbSetInitializer.InitializeSets(context);
            currentDbContext.Current = context;
        }
    }
    
    //register in EF Core DI container.
    svcs.DecorateService<IDbSetInitializer, InitializeAsycLocalCurrentDbContext>();

    Introducing ContextValueConveter<TModel, TProvider> abstract class to force to include AsyncLocalCurrentDbContext parameter for the implementations.

    internal abstract class ContextValueConveter<TModel, TProvider> : ValueConverter<TModel, TProvider>, IContextValueConveter
    {
        protected ContextValueConveter(AsyncLocalCurrentDbContext asyncLocalCurrentDb,
                                       Expression<Func<TModel, TProvider>> convertToProviderExpression,
                                       Expression<Func<TProvider, TModel>> convertFromProviderExpression,
                                       ConverterMappingHints? mappingHints = null) : base(convertToProviderExpression, convertFromProviderExpression, mappingHints)
        {
    
        }
    }
    
    internal interface IContextValueConveter { }

    Implement ContextValueConveter<TModel, TProvider> by PasswordContextValueConvter in demo.
    reference asyncLocalCurrentDb instance in expression tree.
    PS : EncryptPassword and DecryptPassword are extension methods for DbContext.

    internal class PasswordContextValueConvter : ContextValueConveter<string, string>
    {
        public PasswordContextValueConvter(AsyncLocalCurrentDbContext asyncLocalCurrentDb)
                                          : base(asyncLocalCurrentDb,
                                                 password => asyncLocalCurrentDb.Current.EncryptPassword(password),
                                                 encryptPassword => asyncLocalCurrentDb.Current.DecryptPassword(encryptPassword))
        {
    
        }
    }

    EncryptPassword and DecryptPassword method use application provider to get IDataProtect to encrypt or decrypt data.

    public static string EncryptPassword(this DbContext dbcontext, string password)
    {
        Console.WriteLine($"EncryptPassword : current dbContext id : {dbcontext.ContextId}");
        var appProvider = dbcontext.GetService<IDbContextOptions>()?.Extensions.OfType<CoreOptionsExtension>().FirstOrDefault()?.ApplicationServiceProvider!;
    
        var dataProtector = appProvider.GetRequiredService<IDataProtectionProvider>()
                                       .CreateProtector("password");
    
        var value = dataProtector.Protect(password);
    
        Console.WriteLine($"Password ({password})  is encrypted to {value}");
        Console.WriteLine();
    
        return value;
    }
    
    
    public static string DecryptPassword(this DbContext dbcontext, string decrypted)
    {
        Console.WriteLine($"DecryptPassword : current dbContext id : {dbcontext.ContextId}");
    
        var appProvider = dbcontext.GetService<IDbContextOptions>()?.Extensions.OfType<CoreOptionsExtension>().FirstOrDefault()?.ApplicationServiceProvider!;
    
        var dataProtector = appProvider.GetRequiredService<IDataProtectionProvider>()
                                       .CreateProtector("password");
    
        var password = dataProtector.Unprotect(decrypted);
    
        Console.WriteLine($"Decrypted password ({decrypted}) is decrypted to {password}");
        Console.WriteLine();
    
        return password;
    }

    Register PasswordContextValueConvter for Password property in OnModelCreating method.

    b.Property(x => x.Password)
     .HasContextValueConversion<PasswordContextValueConvter>();

    Program.cs

    var svcs = new ServiceCollection();
    svcs.AddDataProtection().SetApplicationName("test");
    svcs.AddDbContext<MyDbContext>(b =>
    {
        b.UseInMemoryDatabase("db");
    
        // add context value conversion services in EF Core DI container.
        b.UseContextValueConversion();
    });
    
    var rootProvider = svcs.BuildServiceProvider();
    
    using (var scope = rootProvider.CreateScope())
    {
        var dbContext = scope.ServiceProvider.GetRequiredService<MyDbContext>();
        dbContext.Users.Add(new User()
        {
            Name = "test",
            Password ="pwd",
        });
        await dbContext.SaveChangesAsync();
    
        var user = await dbContext.Users.FirstAsync();
        Console.WriteLine($"Password : {user.Password}");
        Console.WriteLine();
    }
    
    
    using (var scope = rootProvider.CreateScope())
    {
        var dbContext = scope.ServiceProvider.GetRequiredService<MyDbContext>();
        var user = await dbContext.Users.FirstAsync();
        Console.WriteLine($"Password : {user.Password}");
    }
    
    Console.ReadKey();

    Console output: the different dbContext ids are displayed on the screen, means can get current dbcontext in value converter.
    image

  17. removed their assignment
    on Aug 31, 2024
  18. TheConstructor commented on Oct 21, 2024

    @TheConstructor

    @Li7ye does your workaround work with EF Core 9 rc2? We recently had trouble using non-static fields and methods in conversions, when the field is projected during a query. This worked fine in EF Core 8.

  19. roji commented on Oct 21, 2024

    @roji
    Member

    @TheConstructor if you have a scenario that worked in EF Core 8 but no longer works in 9, please submit a new issue with a minimal repro - we'd want to take a look.

  20. TheConstructor commented on Oct 22, 2024

    @TheConstructor

    @TheConstructor if you have a scenario that worked in EF Core 8 but no longer works in 9, please submit a new issue with a minimal repro - we'd want to take a look.

    I hope #34956 can be understood; I am a bit tired right now. Perfect solution mid-term would likely be, if this issue would be implemented.

  21. roji commented on Oct 23, 2024

    @roji
    Member

    @TheConstructor as of now #34956 has been closed as already fixed in 9.0 - it would be good if you could check and confirm whether that's the case.

  22. smarts commented on Jan 28, 2025

    @smarts

    Add my 👍🏼 to this issue. We have a scenario where a Value Object (VO) needs to perform some validation upon constructor invocation based on some options (e.g., IOptions<FooOptions>). Ideally we'd inject the options into the value converter and pass the necessary value(s) from the options to the VO's constructor or factory method so that the VO can decide whether to perform the validation.

  23. added theissue type on Jun 15, 2025
  24. marked ValueConverter for entity. #32222 as a duplicate of this issue on Jun 16, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions