Entity Framework 6 - update entity value during loading

49 Views Asked by At

I have a table in SQL Server which has encrypted data in one column. But not for all rows, there is a complex logic in the background.

On the other side, I have a web app which uses Entity Framework 6 for data access. When I need save data I override method

public override int SaveChanges()

in my DbContext.

Here I can encrypt data before saving to database. This works well.

But now I need to decrypt data when being loaded from the database, before mapping. I thought I can override

public override DbSet<TEntity> Set<TEntity>()

method in the DbContext where I use same logic. But it seems this method is called after mapping so changes has no effect (I can not see them in UI).

Is there any way how to set this logic for specific entity type in one place for whole app?

2

There are 2 best solutions below

1
Mostafa Sabeghi On

I already did the same thing you want to do by adding a new property to my model like this :

[Required]
[MaxLength(50)]
public String UserName { set; get; } 

[NotMapped]
public string DecryptedUserName
{
    get { return Decrypt(UserName); } 
}

Please let me know if you try this

0
Honza K. On

I solved this problem by using DbCommandInterceptor. Here I can override ReaderExecuted method where I can modify data in database context. This changes are propagated to application.