EntityFramework Core 2 - ValueGeneratedOnAddOrUpdate

时间:2018-04-20 12:39:28

标签: c# asp.net-core .net-core entity-framework-core

我有一个场景,我的模型有CreatedOn和UpdatedOn字段,并按照我在EF Core文档中找到的内容实现了我的课程,如下所示

builder.Entity<Registro>(b =>
    {
        b.Property<DateTime>("CreatedOn")
            .IsRequired()
            .ValueGeneratedOnAdd()
            .HasDefaultValueSql("GETUTCDATE()");

        b.Property<DateTime>("UpdatedOn")
            .IsRequired()
            .ValueGeneratedOnAddOrUpdate()
            .HasDefaultValueSql("GETUTCDATE()"); ;
    });

public class Registro
{
    public Guid Id { get; set; }
    public string Nome { get; set; }
}

在插入时,两个字段都以正确的值保存,但是更新并没有像我预期的那样发生,UpdatedOn保存了保存值。它还遵循我如何进行实体更新

public void Put(Guid id, [FromBody]string value)
{
    var r = context.Registros.SingleOrDefault(x => x.Id == id);

    r.Nome = value;

    context.SaveChanges();
}

1 个答案:

答案 0 :(得分:5)

要使您的UpdatedOn时间戳自动更新,您可以选择的一种方法是实现描述功能的接口并重载DbContexts SaveChanges方法。

public interface IUpdateable 
{ 
    DateTime UpdatedOn { get; set; }  
}

public class Registro : IUpdateable
{
    public Guid Id { get; set; }
    public string Nome { get; set; }
    public DateTime UpdatedOn { get; set; }
}

然后在你的Context类

public override int SaveChanges()
{
    var currentDateTime = DateTime.Now;
    var entries = ChangeTracker.Entries().ToList();

    // get a list of all Modified entries which implement the IUpdatable interface
    var updatedEntires = entries.Where(e => e.Entity is IUpdateable)
            .Where(e => e.State == EntityState.Modified)
            .ToList();

    mutableEntires.ForEach(e =>
    {
        ((IUpdateable)e.Entity).UpdatedOn = currentDateTime;
    });


    return base.SaveChanges();
}