How to prevent a column update in EF Core 3.1?

流过昼夜 提交于 2020-07-22 03:55:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!