I have a column that is managed entirely by my DB--a default value is set, then it is changed only by triggers after that. I can't find a way to prevent EF from ever attempting to update that column while still allowing me to read from it.
Generated properties aren't the answer, as the docs say an explicit value will overwrite the DB. I'm not sure I understand that logic, as the whole point in my mind should be that EF _never_ updates the column.
How can I ensure that EF will never touch a column during insert or update?
Hi vaindil,
I believe [NotMapped] or entity.Ignore(x=>x.ThisProperty) maybe what you are after. Just depends if you are using the FluentAPI or Data Annotations to setup your entities.
@Wayne-Mather Using Ignore()
causes EF to completely ignore that property--it doesn't read it from the DB or write back to it.
@vaindil If you want EF to completely ignore any changes made to the property and always get the value from the database, then you can set it to StoreGeneratedAlways
:
C#
modelBuilder
.Entity<Foo>()
.Property(e => e.Bar)
.ValueGeneratedOnAddOrUpdate()
.Metadata.IsStoreGeneratedAlways = true;
If you want EF to not allow changes by throwing if an attempt it made to make a change, then you can set it to IsReadOnlyAfterSave
and/or IsReadOnlyBeforeSave
using similar code.
@ajcvickers Awesome, that's perfect. Thank you so much, I really appreciate it!
Don't work in .NET Core 3.1
In EF Core 3.1.1 it works like this
modelBuilder
.Entity<Foo>()
.Property(e => e.Bar)
.ValueGeneratedOnAddOrUpdate()
.Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore);
Most helpful comment
@vaindil If you want EF to completely ignore any changes made to the property and always get the value from the database, then you can set it to
StoreGeneratedAlways
:C# modelBuilder .Entity<Foo>() .Property(e => e.Bar) .ValueGeneratedOnAddOrUpdate() .Metadata.IsStoreGeneratedAlways = true;
If you want EF to not allow changes by throwing if an attempt it made to make a change, then you can set it to
IsReadOnlyAfterSave
and/orIsReadOnlyBeforeSave
using similar code.