2012-12-19 6 views
7

시작해 볼 수 있는지 확신 할 수 없습니다. 제네릭을 배우고 있으며 내 응용 프로그램에 여러 개의 저장소가 있습니다. 제네릭 형식을 사용하고 모든 리포지토리에서 상속받을 수있는 인터페이스로 변환하는 인터페이스를 만들려고합니다. 이제 내 질문에.Entity Framework에서 제네릭을 사용하려고 시도합니다.

찾을 항목을 결정하기 위해 제네릭을 사용할 수 있습니까?

public IEnumerable<SomeClass> FindBy<A>(A type) 
{ 
    return _context.Set<SomeClass>().Where(x => x. == type); // I was hoping to do x.type and it would use the same variable to search. 
} 

조금 더 명확히하기 위해 문자열, int 또는 검색 할 유형을 고려했습니다. 내가 무엇을 바라고하는 것은 내가 뭔가에 전달 된 변수와 동일한 x.something을 말할 수있다.

내가

public IDbSet<TEntity> Set<TEntity>() where TEntity : class 
{ 
    return base.Set<TEntity>(); 
} 

어떤 제안을 사용하여 내 dbcontext에 대한 저장소를 설정할 수 있습니까?

답변

4

작업 :

public interface IRepository<T> 
{ 
    ... // other methods 
    IEnumerable<T> FindBy(Expression<Func<T, bool>> predicate); 
} 

당신을 linq을 사용하여 유형을 조회하고 저장소 클래스를 호출하는 코드에서 조회를 지정할 수 있습니다. 이 같은

public IEnumerable<SomeClass> FindBy(Expression<Func<SomeClass, bool>> predicate) 
{ 
    return _context.Set<SomeClass>().Where(predicate); 
} 

그리고 전화 :

var results = repository.FindBy(x => x.Name == "Foo"); 

그리고 그것은 일반적인 표현의 주어진, 각 저장소에 그것을 구현하지 않아도, 당신은 일반적인 기본 저장소에있을 수 있습니다. A는 SomeClass에서 파생 된 경우

public IEnumerable<T> FindBy(Expression<Func<T, bool>> predicate) 
{ 
    return _context.Set<T>().Where(predicate); 
} 
+2

개인적으로이 방법이 마음에 들지만 많은 사람들은 그렇지 않습니다. 이것은 리포지토리의 사용자가 EF가 안전하고 어떤 것이 아닌지에 대해 알 필요가 있음을 의미합니다. 이는 누설 된 추상화이기 때문입니다. – stevenrcfox

0

인터페이스 및 추상 클래스의 조합을 사용하여이를 정확하게 수행합니다.

public class RepositoryEntityBase<T> : IRepositoryEntityBase<T>, IRepositoryEF<T> where T : BaseObject 
// 
public RepositoryEntityBase(DbContext context) 
    { 
     Context = context; 
//etc 

public interface IRepositoryEntityBase<T> : IRepositoryEvent where T : BaseObject //must be a model class we are exposing in a repository object 

{ 
    OperationStatus Add(T entity); 
    OperationStatus Remove(T entity); 
    OperationStatus Change(T entity); 
    //etc 

는 파생 클래스는 몇 객체 구체적인 방법이나 실제로 아무것도 가질 수 있고이 같은 Expression<Func<T, bool>> 대신 A를 사용하는 경우 단지

public class RepositoryModule : RepositoryEntityBase<Module>, IRepositoryModule{ 
    public RepositoryModule(DbContext context) : base(context, currentState) {} 
} 
//etc 
관련 문제