Entity Framework: Setting update timestamp

前端 未结 4 1545
囚心锁ツ
囚心锁ツ 2020-12-29 13:14

All of our database tables have UpdateUserID and UpdateTS. I\'d like to have this set if my entity has changes. Is there a way I can have this update on the spot condition

4条回答
  •  Happy的楠姐
    2020-12-29 13:44

    I couldn't get the solution proposed by @eric-j to work, it only set the dates when creating a new object but not when updating.

    I found this solution and modified it to look similar. Have tried out it, and it works like a charm.

    public override int SaveChanges()
    {
        var now = DateTime.UtcNow;
    
        var entries = ChangeTracker
            .Entries()
            .Where(e => e.State == EntityState.Added || e.State == EntityState.Modified);
    
        foreach (var entry in entries)
        {
            if (entry.Entity is IHasLastModified lastModified)
            {
                lastModified.LastModified = now;
                if (entry.State == EntityState.Added)
                {
                    lastModified.CreatedDate = now;
                }
            }
        }
    
        return base.SaveChanges();
    }
    

提交回复
热议问题