2017-03-04 84 views
0

我在實體框架中使用Repository模式開發項目。我收到一個錯誤。這是,當我嘗試刪除一個實體,我得到這個錯誤附加信息:該對象不能被刪除,因爲它不是在ObjectStateManager找到。C#實體框架庫模式

我的代碼是在這裏SERVIS類

public void DeleteRoom(RoomDto roomDto) 
{  
    var room = (from od in context.Rooms 
       where od.OdaId == roomDto.OdaId 
       select od).SingleOrDefault(); 
     odaRepository.DeleteRoom(room); 
} 

在我的倉庫類的代碼是

public void DeleteRoom(T entity) 
{ 
    Context.Set<T>().Remove(entity); 
    Context.SaveChanges(); 
    Context = new Yurt_DBEntities(); 
} 

請幫我

+1

上下文變量不要重新分配給新的實例,特別是如果你不 – pinkfloydx33

回答

0

這意味着實體未連接。它沒有被相同的上下文加載。嘗試這個。

public void DeleteRoom(T entity) 
{ 
    Context.Attach(entity); 
    Context.DeleteObject(entity); 
    Context.SaveChanges(); 
} 
+0

我試圖處置,而是因爲我使用的通用實體類似這樣的公共無效DeleteRoom(T實體)沒有工作 Context.Set ().Remove(entity); Context.SaveChanges(); Context = new Yurt_DBEntities(); } –