2010-11-15 69 views
0

您好我想用對象的所有屬性構造動態實體框架Linq查詢。示例使用對象的所有屬性構造動態LINQ查詢

我想: - 1)對象測試有5個公共屬性。 2)我想遍歷這個對象並檢查每個字符串屬性是否爲空或空。 3)如果沒有,我想編寫一個查詢,它會附加一個where條件來搜索實體和這個屬性的值。

public void CheckMyEntity(IQueryable<ABCEty> _allABCs, MyEntity _MyEntityProperty) 
    { 
     foreach (var prop in _MyEntityProperty.GetType().GetProperties()) 
     { 
      if (!String.IsNullOrEmpty(prop.GetValue(_MyEntityProperty,null).ToString())) 
      { 
       _allABCs = _allABCs.Where(temp => (temp.ABCMyEntitys.All(MyEntity => MyEntity.MyEntity.<<I cant insert the property here>> == prop.GetValue(_MyEntityProperty,null)); 
      } 
     } 
    } 

任何幫助將是非常有用的!謝謝!

回答

3

你可以把每一個的PropertyInfo爲lambda表達式,並傳遞到查詢

public static void CheckMyEntity(IQueryable<ABCEty> _allABCs, MyEntity _myEntity) 
{ 
    foreach (var propertyInfo in _myEntity.GetType().GetProperties()) 
    { 
     if (!String.IsNullOrEmpty(propertyInfo.GetValue(_myEntity, null).ToString())) 
     { 
      //access to modified closure 
      PropertyInfo info = propertyInfo; 
      _allABCs = _allABCs.Where(temp => temp.ABCMyEntitys.All(GenerateLambda(_myEntity, info))); 
     } 
    } 
    var result = _allABCs.ToList(); 
} 

private static Func<MyEntity, bool> GenerateLambda(MyEntity _myEntity, PropertyInfo propertyInfo) 
{ 
    var instance = Expression.Parameter(propertyInfo.DeclaringType, "i"); 
    var property = Expression.Property(instance, propertyInfo); 
    var propertyValue = Expression.Constant(propertyInfo.GetValue(_myEntity, null)); 
    var equalityCheck = Expression.Equal(property, propertyValue); 
    return Expression.Lambda<Func<MyEntity, bool>>(equalityCheck, instance).Compile(); 
} 
+0

謝謝!!我會試試這個 – ganeshran 2010-11-15 12:38:21

+0

嗨houlgap ,你的方法完美地工作。真棒!!謝謝你! – ganeshran 2010-11-15 14:31:39

0

有一個小的動態Linq庫進行文本評估。 http://www.hanselman.com/blog/TheWeeklySourceCode48DynamicQueryableMakesCustomLINQExpressionsEasier.aspx

Dim query = Northwind.Products 
      .Where("CategoryID=2 And p.UnitPrice>3") 
      .OrderBy("SupplierID") 

簡單地把這個類做的文字評價,並將其轉換成一個LINQ表達式樹,大多數LINQ提供像實體框架可以處理。

+0

謝謝!我會檢查這個 – ganeshran 2010-11-15 10:25:23

+0

嗨我試過這個。問題是我的動態查詢直接不在實體上。它是IQueryable實體的IEnumerable屬性。我嘗試將整個字符串傳遞給IQueryable,但它不解析字符串中的lambda表達式。對於例如_allABCs.Where(「temp =>(temp.ABCMyEntitys.All(MyEntity => MyEntity.MyEntity。」+ _ name +「==」+ _value)「);但它沒有工作 – ganeshran 2010-11-15 12:36:35