entity-framework - 如何跳过 Code First 数据库更新中的某些字段?

标签 entity-framework ef-code-first

我有,例如我所有实体类上的“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/

相关文章:

c# - 如何删除 Entity Framework 代码优先数据库中的相关对象?

c# - 在 C# 中回滚 Entity Framework 迁移

c# - MVC3 命名以数字开头的列

c# - ActionResult 中的 MVC 字符串

entity-framework - 如何确定 EF 4.1 中具有引用属性的实体是否脏?

c# - Entity Framework 代码优先中的数据库初始化

c# - Entity Framework 代码优先 : How to seed a database for unit testing

c# - 将某种类型的 IEnumerable 存储到新的 SQL Server 数据库表中的简单方法(代码优先)C#

c# - 如何在 Entity Framework Code First 中建立多对多关联

c# - 如何禁用 EF 代码优先中链接表的级联删除?