问题
I upgraded from .Net Core 2.2 to 3.1 and this functionality has been deprecated
modelBuilder
.Entity<Order>()
.Property(e => e.CreationTime)
.ValueGeneratedOnAddOrUpdate()
.Metadata.IsStoreGeneratedAlways = true;
I need EF to do the Insert but block the update.
Thanks!
回答1:
According to the obsoleted property implementation:
public virtual bool IsStoreGeneratedAlways
{
get => AfterSaveBehavior == PropertySaveBehavior.Ignore || BeforeSaveBehavior == PropertySaveBehavior.Ignore;
set
{
if (value)
{
BeforeSaveBehavior = PropertySaveBehavior.Ignore;
AfterSaveBehavior = PropertySaveBehavior.Ignore;
}
else
{
BeforeSaveBehavior = PropertySaveBehavior.Save;
AfterSaveBehavior = PropertySaveBehavior.Save;
}
}
}
the equivalent code should set BeforeSaveBehavior
and AfterSaveBehavior
to Ignore
.
Also since BeforeSaveBehavior
and AfterSaveBehavior
properties have been replaced with Get
/ Set
method pairs, it would require introducing a temporary variable to hold the property metadata.
Something like this:
var creationTime = modelBuilder
.Entity<Order>()
.Property(e => e.CreationTime)
.ValueGeneratedOnAddOrUpdate()
.Metadata;
creationTime.SetBeforeSaveBehavior(PropertySaveBehavior.Ignore);
creationTime.SetAfterSaveBehavior(PropertySaveBehavior.Ignore);
回答2:
According to the official documentation, IsStoreGeneratedAlways become obsolete from 3.1.
Microsoft.EntityFrameworkCore.Metadata Assembly:
If Throw, then an exception will be thrown if a new value is assigned to this property after the entity exists in the database.
If Ignore, then any modification to the property value of an entity that already exists in the database will be ignored.
You should try something like this:
modelBuilder
.Entity<Order>()
.Property(e =>.CreationTime).Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore);
来源:https://stackoverflow.com/questions/59977743/how-to-prevent-a-column-update-in-ef-core-3-1