How to prevent a column update in EF Core 3.1?

c# ef-core-3.0 ef-core-3.1 entity-framework-core

Question

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
1
1/30/2020 2:42:46 AM

Accepted 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
1/30/2020 2:40:42 AM

Popular Answer

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


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow