0

에 새/변경된 엔터티를 각각 저장하고 수정 된 모델 만 업데이트하려고했습니다. 말하자면, "Article"을 모델로 이야기합니다. 다음 방법은 "기사"라는 클래스에서 구현 : 나는 컨트롤러 액션에 수정 된 문서를 저장할 때마다Entity Framework

public static void SaveArticle(Article article) 
    { 
     if (article.Id == 0) 
     { 
      webEntities.Articles.Add(article); 
     } 
     else 
     { 
      webEntities.Articles.Attach(article); 
      webEntities.Entry(article).State = EntityState.Modified; 
     } 

     webEntities.SaveChanges(); 
    } 

그래서, 난 그냥 호출해야 "Articles.SaveArticle (myArticle를);", 예상대로 작동합니다.
지금까지는 그렇게 좋았지 만 모든 모델/엔티티에 대해 이것을 중복 구현해야한다는 것을 의미합니다.

그런 다음 템플릿 패턴과 비슷한 것으로 생각했습니다. 나는. "Article"이 "Entity"로부터 상속받는 "Entity"라는 클래스.

public static void SaveEntity(Entity entity) 
    { 
     if (Entity.Id == 0) // <-- Problem 1 
     { 
      webEntities.Entities.Add(entity); // <-- Problem 2 
     } 
     else 
     { 
      webEntities.Entities.Attach(entity); // <-- Problem 3 
      webEntities.Entry(entity).State = EntityState.Modified; // <-- Problem 4 
     } 

     webEntities.SaveChanges(); 
    } 

그래서 내가 중복을 구현할 필요가 없습니다 것입니다하지만 위의 코드에서 언급 한 문제를 해결하는 방법을 알고하지 않습니다
또한, "엔티티"라는 클래스는 다음과 같이 정적 메서드가 포함되어 있습니다. 너무 복잡하다고 생각하거나 내 문제의 모범 사례는 무엇입니까?

미리 감사드립니다.

친절한 답변

+0

엔티티 프레임 워크 4 또는 5를 사용하고 있습니까? –

+0

버전 4.4.0.0과 런타임 버전 v4.0.30319가 표시됩니다. –

+0

'DbContext' 또는'ObjectCOntext'를 사용합니까? –

답변

1

제네릭을 사용하십시오.

public static void Save<T>(T entity) 
    where T : class 
{ 
    webEntities.Set<T>().AddOrUpdate(entity); 
    webEntities.SaveChanges(); 
} 

AddOrUpdate는 System.Data.Entity.Migrations의 확장 방법.

+0

완벽한, 고맙습니다. 처음 AddOrUpdate가 알려지지 않은 이유가 궁금했지만 처음에는 "System.Data.Entity.Migrations" 수동으로 (컴파일러에서 제안하지 않음) –