2013-11-28 2 views
1

속성을 DbSet으로 캐스팅하고 load 메서드를 호출하는 메서드를 작성하려고합니다.캐스트 DbSet <T> 및 호출 메서드

나는 시도 다음

var value = propertyInfo.GetValue(em, null) as DbSet; 
//Not working, because it always returns null 

var value = propertyInfo.GetValue(em, null) as DbSet<T>; 
//Not working, because its a syntax error and doesnt even compile (giving error 'Cannot resolve symbol T') 

var value = propertyInfo.GetValue(em, null) as DbSet<TEntity>; 
//Not working, because its a syntax error and doesnt even compile (giving error 'Cannot resolve symbol TEntity') 

하지만 올바른 유형에게 그 작업을 지정하는 경우에만 :

var value = propertyInfo.GetValue(em, null) as DbSet<TempTable>; 

가 어떻게 밖으로 TEMPTABLE를 지정하여이 문제를 해결할 수 있습니까? 아마도 이런

+1

"그러나 올바른 유형의 작업을 지정할 때만 : "- 잘 작동하지 않을 때 어떤 일이 발생하는지 정확하게 말할 수 있습니까? 오류/예외/등은 무엇입니까? 또한 : 여기에'T'와'TEntity'는 무엇입니까? 그것은'TempTable'과 동일하지만 generic 형식 매개 변수입니까? –

+0

@MarcGravell : 내 편집 좀 봐, 난 그냥 T 또는 TEntity 희망이있다, 그 일을하는 방법 thats 또한 시도했지만 이것도 null을 반환합니다. –

답변

3
var value = propertyInfo.GetValue(em, null) as DbSet; 
//Not working, because it always returns null 

; DbSet<TEntity>DbSet에서 상속되지 않으므로 예, 항상 null이됩니다.

//Not working, because its a syntax error and doesnt even compile (giving error 'Cannot resolve symbol T') 

대화 할 내용의 유형을 알아야합니다. 당신은 제네릭이 아닌 IEnumerable/IQueryable API를 사용할 수 있지만 내가 dynamic 수 있습니다 여기에 가장 적합한 악을 의심 :

dynamic val = propertyInfo.GetValue(em, null); 
EvilMethod(val); 

//... 

void EvilMethod<T>(DbSet<T> data) 
{ 
    // this will resolve, and you now know the `T` you are talking about as `T` 
    data.Load(); 
} 

또는 단지 통화 할 경우 Load :

dynamic val = propertyInfo.GetValue(em, null); 
val.Load(); 
+0

처음에는 동적으로 해봤지만, 그렇게 할 때 Load() 메소드가 DbSet 의 메소드가 아니라는 예외가 발생합니다. 그 이유는 정적 확장이 동적으로 적용될 수 있기 때문입니다. C#의 버그? –

+0

EvildMethod 메서드가 작동하지만 마지막 예제에서와 같이 .Load()를 호출하면 작동하지 않습니다. 내 이전 게시물에서 오류 메시지와 함께. (DbSet 에는 Load()의 정의가 포함되어 있지 않습니다. –

+0

@Rand 예. 확장 메서드이기 때문에입니다. 그것 때문에, 당신이 실제로'DbSet ' –

1

뭔가 :

var setMethod = typeof(MyDataContext) 
    .GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance) 
    .Where(m => m.Name == "Set") 
    .Where(m => m.IsGenericMethod) 
    .Select(m => m.MakeGenericMethod(typeof(TEntity))) 
    .SingleOrDefault(); 

var value = setMethod.Invoke(myDataContextInstance, null); 
3

이 시도 : 실제로

var value = propertyInfo.GetValue(em, null) as IQueryable; 
value.Load(); 
+0

확장 방법입니다. http://msdn.microsoft.com/en-us/library/system.data.entity.queryableextensions.load(v=vs.113).aspx – Reda

+0

나는 고쳐 줘서 고마워. –