2013-10-28 2 views
3

BLLEF 저장소 패턴 - 업데이트 논리

public void Update(Product product) 
{ 
    if (repository.GetProductById(product.ID) != null) 
    { 
     repository.Update(product); 
    } 
else 
    { 
    // Display errorrs 
    } 
} 

에서 저장소에 내가 웹 사이트를 실행하면이 오류

을 보여

public void UpdateProduct(Product product) 

{ 

_dbContext.Entry(product).State = EntityState.Modified; 

_dbContext.SaveChanges(); 

} 



public Product GetProductById(int id) 

{ 

return _dbContext.Products.Find(id); 

} 

"같은 키를 가진 개체가 이미 ObjectStateManager에서 동일한 키를 가진 여러 객체를 추적 할 수 없습니다. "

나는 무슨 일이 일어 났는지 안다. GetProductByID()를 호출하여 DbContext에 연결된 제품 엔터티를 호출합니다. 그래서 Update()를 호출하면 Product 엔터티가 복제됩니다. Update()에서 DbContext에 존재했던 엔터티를 첨부했기 때문에.

해결하려면. 나는 Update() 만 부른다. 그러나 업데이트하기 전에 제품 존재 여부를 확인/삭제하고 싶습니다.

멋진 디자인으로이 문제를 어떻게 해결할 수 있습니까?

당신이 같은 연결을 끊는 엔티티에 대한 데이터베이스를 조회 할 수 있습니다

답변

0

: 당신이 AsNoTracking로 컨텍스트를 설정하면

public bool ProductExists(int id) 
{ 
    return _dbContext.Products.Any(o => o.Id == id); 
} 
0

:

public Product GetProductById(int id) 
{ 
    return _dbContext.Products.AsNoTracking().SingleOrDefault(o => o.Id == id); 
} 

가 또는 다른 곳에서 코드에서이 같은 검사를 할 수있는() 그러면 aspmvc가 메모리의 엔티티에 대한 변경 내용을 추적합니다 (웹에서 원하는 내용).

_dbContext.Products.AsNoTracking().Find(id); 
난 당신이 http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/advanced-entity-framework-scenarios-for-an-mvc-web-application

에서이에 대한 자세한 내용을 추천 할 것입니다

야쉬