如何使用DbEntityEntry处理实体的状态?

时间:2014-03-13 08:26:23

标签: asp.net-mvc entity-framework entity-framework-4 linq-to-entities entity-framework-5

我正在观看John Papa的CodeCamper教程,我遇到了EFRepository类中的代码。并且很难找到我为什么他使用DbEntityEntry以及当我在寻找DbEntityEntry.State属性的细节时,我看到他们一直在谈论一些图像:

在设置实体状态或调用SaveChanges()时,EF会自动在图表中附加分离的对象。

请告诉我这些意味着什么。

以下是类:

public class EFRepository<T> : IRepository<T> where T : class
{
    protected DbContext DbContext { get; set; }
    protected DbSet<T> DbSet { get; set; }

    public EFRepository(DbContext dbContext)
    {
        if (dbContext == null)
        {
            throw new ArgumentNullException("dbContext");
        }
        DbContext = dbContext;
        DbSet = DbContext.Set<T>();
    }

   public virtual void Add(T entity)
    {
        DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
        if (dbEntityEntry.State != EntityState.Added)
        {
            dbEntityEntry.State = EntityState.Added;
        }
        else
        {
            DbSet.Add(entity);
        }
    }

    public virtual void Update(T entity)
    {
        DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
        if (dbEntityEntry.State == EntityState.Detached)
        {
            DbSet.Attach(entity);
        }
        dbEntityEntry.State = EntityState.Modified;
    }

    public virtual void Delete(T entity)
    {
        DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
        if (dbEntityEntry.State != EntityState.Deleted)
        {
            dbEntityEntry.State = EntityState.Deleted;
        }
        else
        {
            DbSet.Attach(entity);
            DbSet.Remove(entity);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

如果你有一个WPF应用程序,你的实体会一直留在内存中,所以你可以这样做:

var cakeProduct = new Product{ProductName = "Cake"};
MyContext.ProductsDbSet.Add();
MyContext.SaveChanges();

和(一段时间后)

cakeProduct.ProductName = "Chocolate Cake";
MyContext.SaveChanges();

MyContext.ProductsDbSet.Remove(cakeProduct);
MyContext.SaveChanges();

但是如果你有一个ASP .Net MVC应用程序,你必须回应一个电话

[HttpPost]
public ActionResult Edit(Product someProduct){
   //someProduct has only just been created in memory
   var context = new MyContext(); //the Context does not exist yet
   context.ProductsRepository.Update(someProduct);
}