我正在尝试为所有记录存储更新日期和创建日期。
我添加Override for SaveChanges方法更新记录时的问题CreatedDate变为null。所以我的问题是,在更新时如何保持CreatedDate不做任何更改。
public override int SaveChanges()
{
try
{
var changeSet = ChangeTracker.Entries();
dynamic obj;
if (changeSet != null)
{
foreach (var entry in changeSet.Where(c => c.State == EntityState.Added))
{
obj = entry.Entity;
obj.CreatedDate = DateTime.UtcNow;
}
foreach (var entry in changeSet.Where(c => c.State == EntityState.Modified))
{
obj = entry.Entity;
obj.ModifiedDate = DateTime.UtcNow;
}
}
}
catch (Exception ex)
{
throw;
}
return base.SaveChanges();
}
答案 0 :(得分:0)
简单,更新时不要传递CreateDate!
if (changeSet != null)
{
foreach (var entry in changeSet.Where(c => c.State == EntityState.Added))
{
obj = entry.Entity;
}
foreach (var entry in changeSet.Where(c => c.State == EntityState.Modified))
{
obj = entry.Entity;
}
}