2011-10-21 3 views
9

나는이 같은 것을 얻을 방법을 찾고 있어요 : 나는 단지 강하게 필드 이름을 입력받을 수 있습니다 볼 수 있듯이 지금까지엔티티 프레임 워크는

string _col1 = "first name"; 
string _name; 
var query = from c in ctx.Customers select c; 
_name = query.FirstOrDefault().[_name]; 

을하지만 난 제공하고 싶습니다 문자열 변수로 사용할 수 있습니다.

+1

? 귀하의 예제에서는 할당 후 _col1을 사용하지 않습니다. 지정하십시오 ... – AJC

+0

문자열 목록의 문자열 값을 기준으로 열 이름을 입력해야 필터링 할 수 없습니다. – Andy

답변

19

EF가 속성의 문자열 이름을 기반으로 속성 값을 가져 오는 방법을 제공하는지는 잘 모르겠지만 리플렉션을 사용할 수는 있습니다.

string name = typeof(Customer) 
    .GetProperty("first name") 
    .GetValue(query.First(), null) as string; 

난 당신이 Customer라고 취급하고있는 EF 클래스를 같은데요.

+1

완벽하게 작동합니다. 감사합니다. – Andy

+0

다행입니다. 답을 정답으로 표시하십시오. 감사. –

+0

항목 컬렉션을 가져 오는 중에 오류가 발생했습니다. – Matt

4

반성을 사용해야합니다. 당신이이 동적으로 선택한 열을 기준으로 필터링하려는 경우, 당신은 이런 식으로 뭔가를 시도 할 수 있습니다 :

string propertyName 
string keyword 

ParameterExpression parameter = Expression.Parameter(typeof(YourType), "x"); 
Expression property = Expression.Property(parameter, propertyName); 
Expression target = Expression.Constant(keyword); 
Expression containsMethod = Expression.Call(property, "Contains", null, target); 
Expression<Func<YourType, bool>> lambda = 
    Expression.Lambda<Func<YourType, bool>>(containsMethod, parameter); 

var companies = repository.AsQueryable().Where(lambda); 

을 나는 당신이 당신이 람 바어를 생성하는 동일한 원리를 사용하여, 특정 열을 선택하면된다하려고 표현을 사용하고 선택에서 (빼기 조건)

var companies = repository.AsQueryable().Where(whatever).Select(lambda); 
+0

여기에 대한 참조가 있습니까? "x"는 무엇을 의미합니까? – Matt

+0

@Matt "x"는'x => x.Property'에서와 같이 람다 표현식을 의미합니다. 참조, 내가 물어 본 질문에서, http://stackoverflow.com/questions/7246715/use-reflection-to-get-lambda-expression-from-property-name. – AJC

0

어떤 이유로 나는 나를 위해 작동하지 않습니다.

내 비슷한 작업 솔루션의 그 :

string name = null; 

// Select the PropertyInfo of the column. 
PropertyInfo propertyInfo = query.First().GetType().GetProperty("first name"); 

if (propertyInfo != null) 
{ 
    try 
    { 
    // Select the content of the column. 
    name = pi.GetValue(query.First(), null).ToString(); 
    } 
    catch (Exception) 
    { 
    // Continue with null-string. 
    } 

}

해당 열을 기준으로 열 또는 필터링을 선택 의미
관련 문제