How to prevent a column update in EF Core 3.1?

4.5k views Asked by At

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!

2

There are 2 answers

0
Ivan Stoev On BEST ANSWER

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);
0
Douglas C On

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);