EntityFramework Core 2 - ValueGeneratedOnAddOrUpdate

.net-core asp.net-core c# entity-framework-core

Question

I have a scenario where my model has the fields CreatedOn and UpdatedOn and following what I found in the documentation of EF Core I implemented my class as follows

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

On insert both fields are saved with the correct value, however the update it does not happen as I expected, the UpdatedOn keeps the save value. It also follows how I am doing the entity update

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

    r.Nome = value;

    context.SaveChanges();
}
1
4
4/20/2018 12:39:28 PM

Accepted Answer

To get your UpdatedOn timestamp to update automatically, one method you could choose is to implement an interface describing the functionality and overload the DbContexts SaveChanges method.

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

And then within your Context class

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 updatedEntries = entries.Where(e => e.Entity is IUpdateable)
            .Where(e => e.State == EntityState.Modified)
            .ToList();

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


    return base.SaveChanges();
}
6
7/25/2019 9:16:56 AM


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