实现Repository模式的Delete方法

时间:2014-09-28 08:50:16

标签: c# entity-framework repository

我找到了一个Repository模式实现。 这种Generic Repository的Delete()方法的实现是否正确?

public virtual void Delete(T entity)
{
    DBEntityEntry entry = this.DbContext.Entry(entity);

    if (entry != EntityState.Deleted)
    {
        entry.State = EntityState.Deleted;
    }
    else
    {
        this.DbSet.Attach(entity);
        this.DbSet.Remove(entity);
    }
}

如果条目的状态为Detached,将条目附加到DbSet时是否会引发错误?

1 个答案:

答案 0 :(得分:2)

如果您的所有实体都有Id(例如,所有从IEntity继承的实体)属性请尝试以下代码:

public interface IEntity
{
   public int Id { get; set; }    
}
// T is IEntity
public virtual void Delete(T entity)
{    
   var ent = this.DbContext.Set<T>().Find(entity.Id);

   if (ent != null)
   {
       this.DbContext.Set<T>().Remove(entity)
   }
}

如果没有,请尝试以下代码:

public virtual void Delete(T entity) {

    DbEntityEntry dbEntityEntry = this.DbContext.Entry<T>(entity);
    if (dbEntityEntry.State != EntityState.Detached) {

        dbEntityEntry.State = EntityState.Deleted;
    }
    else {

        DbSet dbSet = this.DbContext.Set<T>();
        dbSet.Attach(entity);
        dbSet.Remove(entity);
    }
}