2013-08-20 2 views
0

나는 C# asp.net4 mvc 응용 프로그램을 가지고 있습니다. SQL Server에 연결하기 위해 엔티티 프레임 워크를 사용하고 있습니다. Auto Mapper를 사용하여 도메인 모델을보기 모델에 매핑합니다. 제네릭을 사용하여 기본 리포지토리를 만들어 각기 다른 클래스에 대해 메서드를 50 회 작성하는 대신 작성/읽기/업데이트/삭제 작업을 수행하려고합니다. 이것은 내가 지금까지 가지고 있지만 작동하지 않습니다.제네릭을 사용하여 기본 리포지토리를 만들려면

public class BaseRepository<T, U> where T : class 
    { 
     public virtual IEnumerable<T> GetAll() 
     { 
      using (ApplicationEntities context = new ApplicationEntities()) 
      { 
       IEnumerable<T> models = context.Set<T>(); 
       return Mapper.Map<IEnumerable<T>, IEnumerable<U>>(models);     
      } 
     } 
    } 

오류 :

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<U>' to 'System.Collections.Generic.IEnumerable<T>'. An explicit conversion exists (are you missing a cast?)

편집 : 팀 S에 따라, 방법을 업데이트했습니다. 이제 자동 매퍼 오류 만 남아 있습니다.

+0

데시벨은 무엇입니까 : Set<TEntity>() 하나를 가지고 있기 때문에 그리고 당신은, T에 제네릭 제한을 추가해야합니다? 그것은'T'라는 이름의 db 멤버가 아닙니다 –

+0

'db.T' - 당신은 그렇게 할 수 없습니다. 'CreateObjectSet '또는 뭔가를 시도하십시오. –

+0

@SriramSakthivel 미안하지만. db.T 컨텍스트로 변경했습니다. –

답변

2

DbContext.Set<TEntity>() 방법을 사용해야합니다.

public class BaseRepository<T, U> where T : class 
{ 
    public virtual IEnumerable<U> GetAll() 
    { 
     using (ApplicationEntities context = new ApplicationEntities()) 
     { 
      IEnumerable<T> models = context.Set<T>(); 
      return Mapper.Map<IEnumerable<T>, IEnumerable<U>>(models);     
     } 
    } 
} 
+0

귀하의 답변으로 업데이트 된 질문. 이제 자동 매퍼 오류 만 남습니다. –

+0

@That -_- Guy__이 내 대답을 업데이트했습니다. 메서드의 반환 형식이 잘못되었습니다. –

관련 문제