2013-12-08 2 views
0

새 프로젝트를 할당 받았고 EF를 제공하기로 결정했습니다.이 프로젝트에서 나는 데이터를 얻는 데 지속성이 없다는 것을 알았습니다. 일부 캐싱을 구현해야합니다.일반 저장소 EntityFramework 6 구현

리포지토리 패턴에 대한 읽기 나는 많은 코드 샘플 등을 발견했습니다 ... 그들은 나에게 모두 틀린 것처럼 보입니다. 그들은 일대일 리포지토리로 엔티티를 구현합니다.

내 프로젝트에서는 저장하지 않는 등의 데이터를 읽는 것만으로 ... 읽기 만해야합니다. 나는 100 대 저장소를 만들 수 없어 100 대 엔티티가 잘못되었습니다.

나는 간단한 시작하기로 결정하고 난 모든 필요는 이것이다 : 내가 어디다 내가 고민하고하는 것은

public interface IRepository : IDisposable 
{ 
    IEnumerable<T> GetAll<T>() where T : class; 
    IEnumerable<T> Find<T>(Expression<Func<T, bool>> predicate) where T : class; 
    T GetOne<T>(Expression<Func<T, bool>> predicate) where T : class; 
} 

public class Repository : IRepository 
{ 
    public IEnumerable<T> GetAll<T>() where T : class 
    { 
     return ???.ToArray(); 
    } 

    public IEnumerable<T> Find<T>(Expression<Func<T, bool>> predicate) where T : class 
    { 
     return ???.Where(predicate).ToArray(); 
    } 

    public T GetOne<T>(Expression<Func<T, bool>> predicate) where T : class 
    { 
     return ???.Where(predicate).FirstOrDefault(); 
    } 

    public void Dispose() 
    { 
     throw new NotImplementedException(); 
    } 
} 

은 "???" 그게 내 IDBET이어야합니다.

콘크리트 저장소를 구현하려면 어떻게해야합니까? 제안 사항이나 불량 테스트 샘플이 수행 할 수있는 작업은 무엇입니까?

답변

1

먼저

많은 감사, 당신은 더 나은, IQueryable<T> 대신 IEnumerable<T>의 반환하도록 GetAll()Find() 방법을 변경하려면 데이터 세트에 대한 추가 질의를 사용하여 구현 될 것이라고 Linq에 - 투 - 엔티티 그래서.

EF의 구현에서는,이 같은 것을 시도 :

public class EFRepository : DbContext, IRepository 
{ 
    // ctor: 
    // pass a full connecting-string, or "name=someName" from configuration 
    public EFRepository(string connectionStringOrName) : base(connectionStringOrName) 
    { 
      // init sets 
      this.Entities1 = this.Set<EntityOfSomeType>(); 
      this.Entities2 = this.Set<EntityOfOtherType>(); 
    } 

    public IEnumerable<T> GetAll<T>() where T : class 
    { 
     return this.Set<T>().ToArray(); 
    } 

    public IEnumerable<T> Find<T>(Expression<Func<T, bool>> predicate) where T : class 
    { 
     return this.Set<T>().Where(predicate).ToArray(); 
    } 

    public T GetOne<T>(Expression<Func<T, bool>> predicate) where T : class 
    { 
     return this.Set<T>.FirstOrDefault(predicate); 
    } 

    public void Dispose() 
    { 
     base.Dispose(); 
    } 

    // Your DbSets... 
    public IDbSet<EntityOfSomeType> Entities1 { get; set; } 
    public IDbSet<EntityOfAnotherType> Entities2 { get; set; } 
} 

이 reply.Yes에 대한 haim770.Thanks @

+0

(난 당신이 코드 첫번째려고하고 가정으로 DbContext을 사용) 나는 codefirst를 사용하고있다. EF를 처음 사용하고 dbset을 인스턴스화하는 데 문제가 있습니다. DBContext가 가장 가벼운 EF 객체입니까? 다중 스레드 환경에서 사용할 수 있습니까? 제안 사항 – user9969

+0

실제 시나리오에서 좀 더 많은 코드를 추가했습니다. – haim770

+0

'DbContext'가 '가장 가벼운'또는 '무겁지'않은 경우, EF가 접근/모델 데이터를 제공하는 방식 중 하나 일뿐입니다. http://stackoverflow.com/questions/5446316/code-first-vs-model-database-first – haim770