Hi @net 6 newbie,
Below is a work demo, you can refer to:
Author :
public class Author
{
public DateTime UpdatedAt { get; set; }
public string Name { get; set; }
public int Id { get; set; }
}
Then add override SaveChanges in dbContext like:
public class ComputeCore6Context : DbContext
{
public ComputeCore6Context (DbContextOptions<ComputeCore6Context> options)
: base(options)
{
}
public DbSet<ComputeCore6.Models.Author> Author { get; set; } = default!;
public override int SaveChanges()
{
var entries = ChangeTracker
.Entries()
.Where(e => e.Entity is Author && (
e.State == EntityState.Added
|| e.State == EntityState.Modified));
foreach (var entry in entries)
{
var entity = (Author)entry.Entity;
if (entry.State == EntityState.Added)
{
entity.UpdatedAt = DateTime.UtcNow;
}
entity.UpdatedAt = DateTime.UtcNow;
}
return base.SaveChanges();
}
}
In the controller use SaveChanges:
_context.Update(author);
_context.SaveChanges();
result:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Qing Guo