我有一个带有Delete方法的抽象存储库类:
public abstract class MyRepository<C, T> :
IMyRepository<T>
where T : class
where C : ObjectContext, new()
{
private C _entities = new C();
public C Context
{
get { return _entities; }
set { _entities = value; }
}
public virtual void Delete(T entity)
{
_entities.Attach(entity);
_entities.DeleteObject(entity);
_entities.SaveChanges();
}
}
然而这不编译?如何在此处创建通用删除方法?
答案 0 :(得分:0)
而不是这个
private C _entities = new C();
使用 Activator.CreateInstance :
private C _entities = Activator.CreateInstance<T>();
答案 1 :(得分:0)
按如下方式修改Delete
方法
public virtual void Delete(T entity)
{
_entities.CreateObjectSet<T>().Attach(entity);
_entities.DeleteObject(entity);
_entities.SaveChanges();
}
public virtual void Update(T entity)
{
_entities.CreateObjectSet<T>().Attach(entity);
_entities.ObjectStateManager
.ChangeObjectState(entity, System.Data.EntityState.Modified);
_entities.SaveChanges();
}