How to automatically populate CreatedDate and ModifiedDate?

后端 未结 6 2001
失恋的感觉
失恋的感觉 2021-01-31 17:07

I am learning ASP.NET Core MVC and my model is

namespace Joukyuu.Models
{
    public class Passage
    {
        public int PassageId { get; set; }
        publi         


        
6条回答
  •  无人共我
    2021-01-31 17:41

    For those who are using the asynchronous system (SaveChangesAsync) and .NET Core, it's better to override the DbContext's SaveChangesAsync method:

    public override Task SaveChangesAsync(
        bool acceptAllChangesOnSuccess,
        CancellationToken cancellationToken = default(CancellationToken))
    {
        var AddedEntities = ChangeTracker.Entries()
            .Where(E => E.State == EntityState.Added)
            .ToList();
    
        AddedEntities.ForEach(E =>
        {
            E.Property("CreationTime").CurrentValue = DateTime.Now;
        });
    
        var EditedEntities = ChangeTracker.Entries()
            .Where(E => E.State == EntityState.Modified)
            .ToList();
    
        EditedEntities.ForEach(E =>
        {
            E.Property("ModifiedDate").CurrentValue = DateTime.Now;
        });
    
        return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
    }
    

    Also, you can define a base class or an interface for your models with these properties:

    public class SaveConfig
    {
        public DateTime CreationTime { get; set; }
        public DateTime? ModifiedDate { get; set; }
    }
    

提交回复
热议问题