2011-09-09 3 views
7

(아래의 코드는 예제 일 뿐이므로 필요한 이유에 대해 언급하지 마십시오. 예 또는 아니오에 대한 명확한 답변을 주시면 감사하겠습니다. 질문은 나에게도 알려 모호 감사)T가 동적 인 런타임에 Entity-Framework에서 ObjectSet <T>을 얻으려면 어떻게해야합니까?

예, 나는 아래 ObjectSet < T> 얻을 수 있습니다.! 위의 코드는 괜찮 작동

ObjectSet<Users> userSet = dbContext.CreateObjectSet<Users>(); 
ObjectSet<Categories> categorySet = dbContext.CreateObjectSet<Categories>(); 

합니다. 그러나 엔터티 테이블이 동적이어야하므로 형식간에 전환 할 수 있습니다. 아래처럼.

//var type = typeof(Users); 
var type = typeof(Categories); 
Object<type> objectSet = dbContext.CreateObjectSet<type>(); 

위의 코드는 컴파일되지 않습니다.

[편집 :] :

//string tableName = "Users"; 
string tableName = "Categories"; 
ObjectSet objectSet = dbContext.GetObjectSetByTableName(tablename); 
+0

의 중복 가능성 (http://stackoverflow.com/questions/ 232535 ​​/ how-to-use-reflection-to-call-generic-method) – nawfal

답변

4

당신이 How do I use reflection to call a generic method?

var type = typeof(Categories); // or Type.GetType("Categories") if you have a string 
var method = dbContext.GetType.GetMethod("CreateObjectSet"); 
var generic = method.MakeGenericMethod(type); 
generic.Invoke(dbContext, null); 
0

여기에 예제를 사용할 수 내가 여기에 답을 발견했다 내가 원하는 것은 비슷한처럼, 또는 아무것도이다 , http://geekswithblogs.net/seanfao/archive/2009/12/03/136680.aspx. 이는 CRUD와 같은 평범한 작업에 특히 EF가 매핑 한 각 테이블에 대해 여러 개의 리포지토리 개체가 필요 없기 때문에 매우 좋습니다. 이는 정확히 내가 찾고 있었던 것입니다.

+1

이것이 왜 OT 였는지에 대한 이유입니다. "왜 이것이 필요한지에 대해 언급하지 마십시오." 방금 왜 필요한지 설명했다면 즉시 그 대답을 할 수 있습니다. 또한 이것을 확인하십시오 : http://stackoverflow.com/questions/5625746/generic-repository-with-ef-4-1-what-is-the-point/5626884#5626884 일반 저장소가 잘못된 패턴입니다. 특정 저장소의 기반 : http://stackoverflow.com/questions/7110981/the-repository-itself-is-not-usually-tested 관련 질문은 DbContext API에 대한 것이지만 ObjectContext API와 동일합니다. –

+0

아주 좋은 링크입니다. 감사. – Ronald

6

나는 위의 제안을 다음 팅겨으로이 작업을 가지고 : [? 일반적인 방법을 호출 반사를 사용하는 방법]

var type = Type.GetType(myTypeName); 
var method = _ctx.GetType().GetMethod("CreateObjectSet", Type.EmptyTypes); 
var generic = method.MakeGenericMethod(type); 
dynamic objectSet = generic.Invoke(_ctx, null); 
관련 문제