2012-08-24 70 views
0

我有一個刪除方法,這個抽象的倉儲類:通用刪除不起作用?

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

什麼錯誤? – ChrisBint

+0

也許'在哪T:object'而不是'where T:class'? –

+0

'System.Data.Objects.ObjectContext.Attach(System.Data.Objects.DataClasses.IEntityWithKey)'的最佳重載方法匹配有一些無效參數 – Pindakaas

回答

0

而是這個

private C _entities = new C(); 

使用Activator.CreateInstance的:

private C _entities = Activator.CreateInstance<T>(); 
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(); 
    } 
+0

然後,編輯或更新方法是什麼? – Pindakaas

+0

@HanssieTeeuwen:一樣! –

+0

好像這樣:_entities.CreateObjectSet ().Attach(entity); _entities.ObjectStateManager.ChangeObjectState(entity,System.Data.EntityState.Modified); _entities.SaveChanges(); – user603007