Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EntityFramework Core 2 - ValueGeneratedOnAddOrUpdate [duplicate]

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();
}
like image 327
MuhMarigo Avatar asked Mar 06 '23 09:03

MuhMarigo


1 Answers

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();
}
like image 162
Darren Lamb Avatar answered Apr 09 '23 18:04

Darren Lamb