You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Value Converters: Enable passing in some context #12205
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?
Reacted by Nick, Julian Verdurmen, KKamal87, Volodymyr Volodin, jabacrack, Karnz, Rob Janssen, Ivan Monteiro Cantalice, Alejandro Carmona Alfonso, Sparin and 149 more
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.
@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.
@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.
@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 ;)
@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.
@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.
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.
internalclassAsyncLocalCurrentDbContext{privatereadonlyAsyncLocal<DbContext>asyncLocal=new();publicDbContextCurrent{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.
internalclassInitializeAsycLocalCurrentDbContext(AsyncLocalCurrentDbContextcurrentDbContext,IDbSetInitializerinnerlDbSetInitializer):IDbSetInitializer{publicvoidInitializeSets(DbContextcontext){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.
Implement ContextValueConveter<TModel, TProvider> by PasswordContextValueConvter in demo.
reference asyncLocalCurrentDb instance in expression tree.
PS : EncryptPassword and DecryptPassword are extension methods for DbContext.
EncryptPassword and DecryptPassword method use application provider to get IDataProtect to encrypt or decrypt data.
publicstaticstringEncryptPassword(thisDbContextdbcontext,stringpassword){Console.WriteLine($"EncryptPassword : current dbContext id : {dbcontext.ContextId}");varappProvider=dbcontext.GetService<IDbContextOptions>()?.Extensions.OfType<CoreOptionsExtension>().FirstOrDefault()?.ApplicationServiceProvider!;vardataProtector=appProvider.GetRequiredService<IDataProtectionProvider>().CreateProtector("password");varvalue=dataProtector.Protect(password);Console.WriteLine($"Password ({password}) is encrypted to {value}");Console.WriteLine();returnvalue;}publicstaticstringDecryptPassword(thisDbContextdbcontext,stringdecrypted){Console.WriteLine($"DecryptPassword : current dbContext id : {dbcontext.ContextId}");varappProvider=dbcontext.GetService<IDbContextOptions>()?.Extensions.OfType<CoreOptionsExtension>().FirstOrDefault()?.ApplicationServiceProvider!;vardataProtector=appProvider.GetRequiredService<IDataProtectionProvider>().CreateProtector("password");varpassword=dataProtector.Unprotect(decrypted);Console.WriteLine($"Decrypted password ({decrypted}) is decrypted to {password}");Console.WriteLine();returnpassword;}
Register PasswordContextValueConvter for Password property in OnModelCreating method.
varsvcs=newServiceCollection();svcs.AddDataProtection().SetApplicationName("test");svcs.AddDbContext<MyDbContext>(b =>{b.UseInMemoryDatabase("db");// add context value conversion services in EF Core DI container.b.UseContextValueConversion();});varrootProvider=svcs.BuildServiceProvider();using(varscope=rootProvider.CreateScope()){vardbContext=scope.ServiceProvider.GetRequiredService<MyDbContext>();dbContext.Users.Add(newUser(){Name="test",Password="pwd",});awaitdbContext.SaveChangesAsync();varuser=awaitdbContext.Users.FirstAsync();Console.WriteLine($"Password : {user.Password}");Console.WriteLine();}using(varscope=rootProvider.CreateScope()){vardbContext=scope.ServiceProvider.GetRequiredService<MyDbContext>();varuser=awaitdbContext.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.
@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.
@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.
@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.
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.
Activity
blowdart commentedon Jun 1, 2018
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.
HaoK commentedon Jun 1, 2018
So maybe Convert(value, user, "property")?
ajcvickers commentedon Apr 25, 2019
Consider also here the case where conversion needs to call some async method.
divega commentedon Apr 25, 2019
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.
roji commentedon Apr 26, 2019
@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.
ajcvickers commentedon Apr 26, 2019
@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.
StevenRasmussen commentedon Apr 26, 2019
@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 ;)
roji commentedon Apr 26, 2019
@StevenRasmussen do you have a specific scenario in mind that this would enable?
StevenRasmussen commentedon Apr 26, 2019
@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.
17 remaining items
soroshsabz commentedon Mar 13, 2024
ITNOA
Hi,
How many votes needed to start implementation of this feature?
ajcvickers commentedon Mar 13, 2024
@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.
Misiu commentedon Jul 1, 2024
As of today, there are 103 votes.
Li7ye commentedon Jul 20, 2024
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 adbContextinstance is cached in expression tree by closure. So, thedbContextcan 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 setAsycLocal<DbContext>value before any operation. e.g. inDbContextconstructor.AsyncLocalCurrentDbContextisDbContextwrapper class.In addition, must set
AsyncLocalCurrentDbContextvalue atIDbSetInitializer.InitializeSets()timing. BecauseIDbSetInitializer.InitializeSets()is executed inDbContextconstructor.Introducing
ContextValueConveter<TModel, TProvider>abstract class to force to includeAsyncLocalCurrentDbContextparameter for the implementations.Implement
ContextValueConveter<TModel, TProvider>byPasswordContextValueConvterin demo.reference
asyncLocalCurrentDbinstance in expression tree.PS :
EncryptPasswordandDecryptPasswordare extension methods forDbContext.EncryptPasswordandDecryptPasswordmethod use application provider to getIDataProtectto encrypt or decrypt data.Register
PasswordContextValueConvterfor Password property inOnModelCreatingmethod.Program.csConsole output: the different dbContext ids are displayed on the screen, means can get current dbcontext in value converter.

TheConstructor commentedon Oct 21, 2024
@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.
roji commentedon Oct 21, 2024
@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.
TheConstructor commentedon Oct 22, 2024
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.
roji commentedon Oct 23, 2024
@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.
smarts commentedon Jan 28, 2025
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.