实现“通用”机制来处理实体框架中的时态数据

时间:2016-05-31 18:19:50

标签: c# entity-framework temporal

我正在尝试使用Entity Framework来完成更新SQL Server数据库中时态数据的“通用”机制。

我所做的是创建一个名为ITemporalData的“标记”界面,该界面定义了两个需要存在的属性 - DateTime ValidFromDateTime? ValidTo

public interface ITemporalData
{
    DateTime ValidFrom { get; set; }
    DateTime? ValidTo { get; set; }
}

我希望在我的DbContext.SaveChanges()覆盖中实现“通用”方法:

  • 克隆任何ITemporalData对象,这会为我提供一个新对象(EntityState.Added),并将其ValidFrom值设置为当前日期&时间
  • 将原始修改后的条目重置为其数据库值(在实体上调用.Reset()),然后将该“旧”记录的ValidTo设置为当前日期&时间

虽然我可以轻松过滤掉ITemporalData覆盖中修改后的SaveChanges()个对象,如下所示:

public partial class MyDbContext
{
    // override the "SaveChanges" method
    public override int SaveChanges()
    {
        DateTime currentDateTime = DateTime.Now;

        // get the modified entities that implement the ITemporalData interface
        IEnumerable<DbEntityEntry<ITemporalData>> temporalEntities = ChangeTracker.Entries<ITemporalData>().Where(e => e.State == EntityState.Modified);

        foreach (var temporalEntity in temporalEntities)
        {
            // how would I do that, really? I only have an interface - can't clone an interface...... 
            var cloned = temporalEntity.Entity.Clone();

            // and once it's cloned, I would need to add the new record to the correct DbSet<T> to store it

            // set the "old" records "ValidTo" property to the current date&time
            temporalEntity.Entity.ValidTo = currentDateTime;
        }

        return base.SaveChanges();
    }
}

我正在努力克服“克隆修改后的记录”方法 - 我实际上只有ITemporalData接口 - 但克隆(使用AutoMapper或其他方法)总是取决于实际,底层具体数据类型.....

2 个答案:

答案 0 :(得分:2)

要克隆实体,您可以通过反射(Activator.CreateInstance)创建新实例,并通过反射将所有原始(非导航)属性复制到它。最好不要使用自动映射工具,因为它们也会访问导航属性,这可能导致延迟加载(或者至少确保禁用延迟加载)。

如果您不喜欢反射(请注意,自动映射器仍会使用它) - 您也可以从ICloneable继承您的界面,并为每个Clone实体实施ITemporalData方法(如果您的实体是自动生成的 - 请使用部分类)。然后每个实体决定如何克隆,没有任何反射。如果克隆逻辑很复杂(例如,涉及从导航属性克隆相关对象),这种方式也有好处。

要添加实体以更正DbSet,请使用DbContext的无类型Set方法:

this.Set(temporalEntity.GetType()).Add(temporalEntity);

答案 1 :(得分:1)

您可以将此Clone方法添加到您的上下文中:

T Clone<T>(DbEntityEntry<T> entry)
    where T : class
{
    var proxyCreationEnabled = this.Configuration.ProxyCreationEnabled;
    try
    {
        this.Configuration.ProxyCreationEnabled = false;
        var clone = (T)entry.CurrentValues.ToObject();
        Set(clone.GetType()).Add(clone);
        return clone;
    }
    finally
    {
        this.Configuration.ProxyCreationEnabled = proxyCreationEnabled;
    }
}

使用如下:

var cloned = Clone(temporalEntity);

clone.GetType将返回克隆对象的实际类型,而T将是编译时类型ITemporalData

这使用EF自己的基础设施来创建克隆,这无疑比反射更快。

虽然克隆的状态立即设置为Added,但它不会执行延迟加载。但是,确保克隆永远不会成为代理可能更安全,因此,如果您决定使用克隆执行其他操作,则永远不会触发延迟加载。 (感谢Evk的敏锐评论)。