注意:我使用的是实体框架版本 5
在我的通用存储库中,我有Add
,Edit
和Delete
方法如下:
public class EntityRepository<T> : IEntityRepository<T>
where T : class, IEntity, new() {
readonly DbContext _entitiesContext;
public EntityRepository(DbContext entitiesContext) {
if (entitiesContext == null) {
throw new ArgumentNullException("entitiesContext");
}
_entitiesContext = entitiesContext;
}
//...
public virtual void Add(T entity) {
DbEntityEntry dbEntityEntry = _entitiesContext.Entry<T>(entity);
if (dbEntityEntry.State != EntityState.Detached) {
dbEntityEntry.State = EntityState.Added;
}
else {
_entitiesContext.Set<T>().Add(entity);
}
}
public virtual void Edit(T entity) {
DbEntityEntry dbEntityEntry = _entitiesContext.Entry<T>(entity);
if (dbEntityEntry.State == EntityState.Detached) {
_entitiesContext.Set<T>().Attach(entity);
}
dbEntityEntry.State = EntityState.Modified;
}
public virtual void Delete(T entity) {
DbEntityEntry dbEntityEntry = _entitiesContext.Entry<T>(entity);
if (dbEntityEntry.State != EntityState.Detached) {
dbEntityEntry.State = EntityState.Deleted;
}
else {
DbSet dbSet = _entitiesContext.Set<T>();
dbSet.Attach(entity);
dbSet.Remove(entity);
}
}
}
您认为这些方法是否实施得很好?尤其是Add
方法。Add
执行以下方法会更好吗?
public virtual void Add(T entity) {
DbEntityEntry dbEntityEntry = _entitiesContext.Entry<T>(entity);
if (dbEntityEntry.State == EntityState.Detached) {
_entitiesContext.Set<T>().Attach(entity);
}
dbEntityEntry.State = EntityState.Added;
}