2010-07-14 2 views
1

내 리포지토리에 대한 기본 클래스에서 사용할 제네릭 메서드를 만들려고하고 있는데 문제가 있습니다. 여기에 방법은 ...Entity Framework의 일반 리포지토리 메서드에서 오류가 발생했습니다.

 public virtual T First(System.Linq.Expressions.Expression<Func<T, bool>> where, List<string> properties) 
    { 
     IQueryable<T> query = null; 
     if (where != null) 
     { 
      query = _context.CreateQuery<T>(String.Format("[{0}]", typeof(T).Name.ToString())).Where(where); 
     } 
     else 
     { 
      query = _context.CreateQuery<T>(String.Format("[{0}]", typeof(T).Name.ToString())); 
     } 

     foreach (string s in properties) 
     { 
      query = query.Include(s); 
     } 

     T _result = (T)query.First(); 

     return _result; 
    } 

내가 코드를 실행하면 그것이 나에게이 오류 제공 :

'Company' could not be resolved in the current scope or context. Make sure that all referenced variables are in scope, that required schemas are loaded, and that namespaces are referenced correctly. Near escaped identifier, line 1, column 1.

내가이 일을 왜에 대한 아이디어가를, 난 그냥 해결하는 방법을 모른다 그것. 내 ObjectContext는 "회사"라는 개체에 대해 알지 못하기 때문에 "회사"를 알기 때문에이 작업을 수행하고 있다고 생각합니다. 이 문제를 해결하는 방법에 대한 아이디어?

오류는이 라인에서 발생 :

T _result = (T)query.First();

감사합니다!

+0

일반적으로 엔터티 집합 이름은 복수화되어 있으므로 컨텍스트가 회사를 아는 이유입니다. 어떤 EF 버전을 사용하고 있습니까? –

+0

버전 4를 사용하고 있습니다. 그래, 그게 작동하지 않는 이유를 추측하고 있지만 작동하도록하는 방법이 있습니까? –

+1

쿼리가 결과를 반환하지 않는 경우 'First' 대신'FirstOrDefault'를 사용하십시오. – TheCloudlessSky

답변

6

시도 대신

query = _context.CreateQuery<T>(String.Format("[{0}]", typeof(T).Name.ToString())).Where(where); 
+0

이것은 효과가 있습니다. 감사합니다 Yury! 이제 당신이나 다른 누군가가 왜 이것이 효과가 있었는지 설명 할 수 있습니까? –

+1

당신은 오신 것을 환영합니다. 글쎄, 왜이 작품. 'IObjectSet '와'ObjectSet '의 소개는 efv4에서 개선 된 부분 중 하나입니다. 이전 버전에서는 작업 할 엔티티 유형에 대한 엔티티 세트의 이름을 알아야했기 때문에 일반적인 저장소를 만드는 것이 까다로웠습니다. 'Repository '구현의 좋은 예가 하나 있습니다 : 당신이 이미 한 것처럼'Func >'선택자로'Func '을 사용하지 마십시오 : http://devtalk.dk/2009/ 06/09/Entity + Framework + 40 + Beta + 1 + POCO + ObjectSet + 저장소 + And + UnitOfWork.aspx –

6

query = _context.CreateObjectSet<T>().Where(where); 

을 사용하려면, 다음과 같은 뭔가 엔티티 세트 이름을 얻을 :

string entitySetName = context.MetadataWorkspace 
         .GetEntityContainer(context.DefaultContainerName, DataSpace.CSpace) 
         .BaseEntitySets.Where(bes => bes.ElementType.Name == typeof(T).Name).First().Name; 

string name = String.Format("{0}.{1}", context.DefaultContainerName, entitySetName); 

query = context.CreateQuery<T>(name).Where(where); 

이렇게하면 적절한 복수를 해결할 수 쿼리의 이름입니다.

Yury의 방법을 사용하는 것이 가장 좋은 방법입니다.

그런데 EDIT, 쿼리가 어떤 개체를 반환하는 경우에 FirstOrDefault() 대신 First()을 반환해야합니다 (그것은 InvalidOperationException가 발생합니다).

+0

FirstOrDefault()로 변경되었습니다. 도와 주셔서 감사합니다! –