我有,例如我所有实体类上的“CreateDate”属性,使用 EF 4.3 Code First。我想阻止对此字段的任何更改发送到数据库,除非首次创建对象时。
现在我可以将此属性设置为只读,但我使用的是 MVC4 前端,这需要在 HTTP POST 操作期间实例化一个新对象并将其绑定(bind)到传入的属性值。然后我可以读取原始对象并根据该对象设置值,这不太高效,或者将值存储在隐藏字段中,这不太安全。
当我的 DbContext 保存更改时,我最好简单地抑制对此字段的任何更新。我可以这样做吗?怎么办?
最佳答案
我将为具有 CreateDate
的实体使用标记接口(interface),然后覆盖 DbContext.SaveChanges
,然后在 ChangeTracker
的帮助下code> 设置或重置 CreatedAt
值。
也许这听起来很复杂,但我创建了一个小示例,您可以从中开始:
public interface ICreatedAt
{
DateTime CreatedAt { get; set; }
}
public class MyEntity : ICreatedAt
{
public int Id { get; set; }
public DateTime CreatedAt { get; set; }
}
public class MyContext : DbContext
{
public DbSet<MyEntity> MyEntities { get; set; }
public override int SaveChanges()
{
foreach (var entry in ChangeTracker.Entries<ICreatedAt>())
{
if (entry.State == System.Data.EntityState.Added)
{
entry.Entity.CreatedAt = DateTime.Now;
}
if (entry.State == System.Data.EntityState.Modified)
{
entry.Entity.CreatedAt =
entry.OriginalValues.GetValue<DateTime>("CreatedAt");
}
}
return base.SaveChanges();
}
}
关于entity-framework - 如何跳过 Code First 数据库更新中的某些字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10671397/