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();
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With