2011-10-21 18 views
9

私はこのような何かを得るために方法を探しています:私は、私だけ強くフィールド名を入力した得ることができます見ることができる限りEntity Frameworkのは

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

アイテムコレクションを1つではなく取得するとエラーが発生します。 – Matt

4

これにはリフレクションを使用する必要があります。あなたはdynamicly選択した列でフィルタしようとしている場合は、このような何かを試すことができます。

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. 
    } 

}