如何防止 EF Core 3.1 中的列更新?

How to prevent a column update in EF Core 3.1?

我从 .Net Core 2.2 升级到 3.1,此功能已被弃用

modelBuilder
.Entity<Order>()
.Property(e => e.CreationTime)
.ValueGeneratedOnAddOrUpdate()
.Metadata.IsStoreGeneratedAlways = true;

我需要 EF 来执行插入但阻止了更新。

谢谢!

根据废弃属性 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;
        }
    }
}

等效代码应将 BeforeSaveBehaviorAfterSaveBehavior 设置为 Ignore

此外,由于 BeforeSaveBehaviorAfterSaveBehavior 属性已替换为 Get / Set 方法对,因此需要引入一个临时变量来保存 属性元数据。

像这样:

var creationTime = modelBuilder
    .Entity<Order>()
    .Property(e => e.CreationTime)
    .ValueGeneratedOnAddOrUpdate()
    .Metadata;
creationTime.SetBeforeSaveBehavior(PropertySaveBehavior.Ignore);
creationTime.SetAfterSaveBehavior(PropertySaveBehavior.Ignore);

根据官方documentation,IsStoreGeneratedAlways 从 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.

你应该尝试这样的事情:

modelBuilder
    .Entity<Order>()
    .Property(e =>.CreationTime).Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore);