简体   繁体   English

使用实体框架更新DBContext类中的创建日期和修改日期字段

[英]Update Created and Modified Date fields in DBContext class with Entity framework

Is there a way I can update or insert entities with their DateCreated and UpdateDate fields set to some date when the entity is being saved. 有没有一种方法可以在保存实体时将其DateCreated和UpdateDate字段设置为某个日期来更新或插入实体。

I have a Data Provider helper class that encapsulated update, add and delete functions for all my data objects. 我有一个数据提供程序帮助程序类,该类封装了我所有数据对象的更新,添加和删除功能。 However when the object is being saved, DateCreated and UpdateDate fields are null and I'm not assigning them the current date. 但是,在保存对象时,DateCreated和UpdateDate字段为null,并且我没有为它们分配当前日期。 I wanna be able to save my objects with those dates assigned. 我想要保存分配了这些日期的对象。 I wanna avoid changing the code everywhere where the save action is performed. 我想避免在执行保存操作的任何地方更改代码。 Is it possible to do it in the DBContext class? 是否可以在DBContext类中执行此操作?

Override DbContext.SaveChanges to implement this cross-cut feature. 重写DbContext.SaveChanges以实现此交叉功能。 If you need to assign properties only to certain entity types, then an interface or class attribute can be used to distinguish them instead of slow Reflection check: 如果只需要将属性分配给某些实体类型,则可以使用接口或类属性来区分它们,而不是进行缓慢的反射检查:

public partial class PostalDbContext
{
    public override int SaveChanges()
    {
        DateTime time = DateTime.Now;

        var entries = ChangeTracker.Entries()
            .Where(entry => entry.Entity is ITrackableEntity)
            .ToList();

        ITrackableEntity x;

        foreach (var entry in entries.Where(e => e.State == EntityState.Added))
        {
            entry.SetPropertyValue(nameof(x.DateCreated), time);
        }

        foreach (var entry in entries.Where(e => e.State == EntityState.Modified))
        {
            entry.SetPropertyValue(nameof(x.DateModified), time);
        }

        return base.SaveChanges();
    }
}

public static class DbEntityEntryEx
{
    public static void SetPropertyValue<T>(this DbEntityEntry entry, string propertyName, T time)
    {
        entry.Property(propertyName).CurrentValue = time;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM