【问题标题】:Entity Framework : entityTypeConfiguration set prop value only on update实体框架:entityTypeConfiguration 仅在更新时设置道具值
【发布时间】:2023-02-06 20:48:41
【问题描述】:

我希望在使用 ValueGeneratedOnUpdate 时,只有在实体已更新(因此实体已经存在)时才会调用特定值生成器。

相反,该值似乎也是在添加时生成的。

这就是我配置创建和更新道具的方式

builder.Property(self => self.CreatedAt)
    .ValueGeneratedOnAdd()
    .HasValueGenerator<UtcTimeValueGenerator>();

builder.Property(self => self.UpdatedAt)
    .ValueGeneratedOnUpdate()
    .HasDefaultValue(null)
    .HasValueGenerator<UtcTimeValueGenerator>();

种子数据。

builder.HasData(new List<Device>
{
    new Device
    {
        Id = 1,
        ParkingLotId = 1,
        Serial = "test",
        SigfoxSerial = "test"
    }
});

发电机

public class UtcTimeValueGenerator : ValueGenerator<DateTime>
{
    public override bool GeneratesTemporaryValues => false;

    public override DateTime Next(EntityEntry entry)
        => DateTime.UtcNow;
}

仅使用 IEntityTypeConfiguration,只有当条目已经存在时,才能为特定列设置日期时间属性。

【问题讨论】:

    标签: c# entity-framework-core entity-framework-6


    【解决方案1】:

    相反,您可以使用 Nullable&lt;DateTime&gt; 生成器。在 Next 函数中,您可以检查状态并决定是否生成新值。

    public class UtcTimeValueGenerator : ValueGenerator<DateTime?>
    {
        public override bool GeneratesTemporaryValues => false;
    
        public override DateTime Next(EntityEntry entry)
            => entry.State == EntityState.Modified ? DateTime.UtcNow : null;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-20
      • 1970-01-01
      • 1970-01-01
      • 2012-03-22
      • 1970-01-01
      相关资源
      最近更新 更多