我正在使用EF 6.1 Code First,并希望使用(简化)模型跟踪历史数据:
public class Customer : IHistoryData<CustomerData>
{
public Guid ID { get; set; }
public virtual ISet<CustomerData> Versions { get; set; }
}
public class CustomerData : HistoricalData
{
public string Name { get; set; }
}
public interface IHistoryData<T> where T : HistoricalData
{
ISet<T> Versions { get; set; }
}
public class HistoricalData
{
public int VersionID { get; set; }
public Guid ParentID { get; set; }
public DateTime ValidFrom { get; set; }
public DateTime? ValidUntil { get; set; }
}
它们以下列方式连接到DbContext:
modelBuilder.Ignore<HistoricalData>();
modelBuilder.Entity<Customer>().ToTable("Customers").HasMany(c => c.Versions).WithRequired().HasForeignKey(cd => cd.ParentID);
modelBuilder.Entity<CustomerData>().Map(m => m.ToTable("CustomerData")).HasKey(cd => new { cd.VersionID, cd.ParentID });
现在要跟踪不同的客户版本,我需要对CustomerData的更改执行插入而不是更新。为此,我挂钩SaveChangesAsync()
的{{1}}:
DbContext
现在我不确定如何实施public override Task<int> SaveChangesAsync()
{
foreach (var entry in ChangeTracker.Entries<HistoricalData>().Where(e => e.State == EntityState.Modified))
{
InsertInsteadOfUpdate(entry);
}
return base.SaveChangesAsync();
}
,这是我到目前为止的方法:
InsertInsteadOfUpdate()
但是,我不知道如何获得private void InsertInsteadOfUpdate<T>(DbEntityEntry<T> oldEntry) where T : HistoricalData
{
// Get a copy of the modified data
var newEntry = ???
// Modified entry has ended
var originalValues = oldEntry.OriginalValues;
originalValues["ValidUntil"] = DateTime.Now;
oldEntry.CurrentValues.SetValues(originalValues);
// New entry has started
newEntry.ValidFrom = DateTime.Now;
Set<T>().Add(newEntry);
}
的新副本/克隆。而且因为我都需要修改&#34; old&#34;条目(设置DbEntityEntry<CustomerData>
)并插入新条目,我需要两个不同的条目。
我该怎么做?或者我完全走错了轨道?
答案 0 :(得分:0)
试试这个:
DbSet<T> dbSet = Context.Set<T>();
T newEntry = dbSet.Create();
dbSet.Attach(newEntry);
newEntry.CurrentValues.SetValues(oldEntry);