2012-03-15 37 views
0

在EntityFramework(和生成的LINQ)中有沒有一種方法可以針對未硬編碼的實體的屬性進行查詢?使用EF查詢編譯時未知屬性

比方說,可以用於搜索功能的東西。

public IList<Entity> Search (string propertyName, object value) { 

    // something that'll do the following 
    return context.Set<Entity>() 
     .Where(x => x.propertyName == value) 
     .ToList() 
     ; 
} 
+0

你最終爲此做了什麼?我發現自己需要同樣的東西。用於多字段搜索。我正在關注這個例子,我使用EF來代替DataTables,就像他們的例子。 http://demos.telerik.com/aspnet-ajax/controls/examples/integration/gridandcombo/defaultcs.aspx?product=grid – hardba11 2012-06-15 22:40:02

回答

0

Property Descriptor

下面的代碼似乎做你需要什麼:

string propertyName = "Length"; 
List<string> testList = new List<string>(); 

testList.Add("String1"); 
testList.Add("String10"); 
testList.Add("String100"); 
testList.Add("String1000"); 

System.ComponentModel.PropertyDescriptorCollection props = System.ComponentModel.TypeDescriptor.GetProperties(typeof(string)); 

System.ComponentModel.PropertyDescriptor desc = props.Find(propertyName, false); 

IEnumerable<object> obj = from env in testList 
      select desc.GetValue(env); 

foreach (object it in obj) 
{ 
    Console.WriteLine(it.ToString()); 
} 
+0

可能是linq-to-objects的一個優雅的解決方案。但是,實體框架查詢將永遠不會轉換爲SQL。 – 2012-03-15 19:26:13

0

你可以建立手動等於表達這樣

private static Expression<Func<TEntity, bool>> BuildEqualExpression<TEntity>(string propertyName, object value) 
{ 
    var param = Expression.Parameter(typeof(TEntity), "x"); 
    var body = Expression.MakeBinary(ExpressionType.Equal, 
     Expression.Property(param, propertyName), Expression.Constant(value)); 

    return Expression.Lambda<Func<TEntity, bool>>(body, new ParameterExpression[] { param }); 
} 

,然後用它在你的LINQ查詢

var expression = BuildEqualExpression<TEntity>(propertyName, value); 
return context.Set<TEntity>().Where(expression).ToList();