2

I am wondering if it it is possible to add SQL to the existing SaveChanges method.

In my model I have specified the fields I want to encrypt by adding a custom Encrypted attribute.

I found how to succesfully encrypt the data with the IDataProtectionProvider. However, it is required that the data is encrypted using SQL's ENCRYPTBYPASSPHRASE() function.

The fieldtypes in my model are type of string (or int in some cases), I want to save them in my database as varbinary.

My question is whether it's possible to create a function that saves my entity to the db, with the needed ENCRYPTBYPASSPHRASE() function, based on the Encrypted attribute specified in the model.

Thanks in advance.

1 Answer 1

2

Option 1. You could override SaveChanges() method and add logic for encrypting there.

public override int SaveChanges()
{
    foreach (var insert in this.ChangeTracker.Entries<IEntityBase>()
        .Where(e => e.State == EntityState.Added))
    {
        if (insert.Entity.Encrypted)
        {
            ...
        }
    }
}

Option 2. You could use a stored procedure for saving the object to database.

Sign up to request clarification or add additional context in comments.

2 Comments

But could I add SQL logic to the SaveChanges method? Like wrapping the field value inside an sql statement, which the SaveChanges will include in it's transaction? If not, I'll look into the possibility of a stored procedure
Did you find a solution? I want to include sql level functions in the SQL generated by save change as well

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.