2015-10-18 24 views
2

我想從動態列表中選擇列表字段名稱爲例如'SecName'並且SecName值等於例如' xxx', 我知道如何在sql中創建它,但我想創建和使用它與實體框架。 像在sql中執行字符串。 我如何在實體框架和linq中做到這一點。 它應該是這樣的從帶有linq字段名稱和字段值的列表中選擇(類似於select命令)

var lst=_efmodel.Tables.where(x=>x.fieldname=="SecName" && x.value=="xxx").tolist(); 

我找語法通過傳遞兩串過濾我的名單,第一個字符串應該是屬性名,其餘的應該是屬性值。

+1

這是不平凡的,不維護,一般一個壞主意。考慮重塑你的數據庫或者重構你的代碼,所以你不需要它。如果你能展示_why_你需要這個例子,這將有所幫助。無論如何見[如何在運行時創建表達式](http://stackoverflow.com/questions/19164308/how-to-create-an-expression-at-runtime-for-use-in-groupby-with-entity- framewor),[在LINQ to EF查詢中構建動態where子句](http://stackoverflow.com/questions/14901430/)等等。 – CodeCaster

回答

0

代碼必須是這樣的嗎?

var lst=_efmodel.Table.Where(x => x.fieldname == <SomeValue>).ToList(); 
+0

它不顯示Fieldname命令。 –

+0

它調用linq的一般模板。我不知道你使用的字段的確切名稱。我正在用你的帖子中的代碼提出建議。 – Mykola

+0

我不知道我的代碼是否正確,我也許應該看起來像這樣,我正在尋找正確的語法,我想要一個語法來過濾我的列表中的兩個字符串,第一個是列名和第二個是列值。 –

2

搜索後,我找到了答案,答案是:

 public class SearchField 
    { 
     public string Name { get; set; } 
     public string @Value { get; set; } 
     //public string Operator { get; set; } 

     public SearchField(string Name, string @Value) 
     { 
      this.Name = Name; 
      [email protected] = @Value; 
      //Operator = "="; 
     } 
    } 
    public class FilterLinq<T> 
    { 
     public static Expression<Func<T, Boolean>> GetWherePredicate(params SearchField[] SearchFieldList) 
     { 

      //the 'IN' parameter for expression ie T=> condition 
      ParameterExpression pe = Expression.Parameter(typeof(T), typeof(T).Name); 

      //combine them with and 1=1 Like no expression 
      Expression combined = null; 

      if (SearchFieldList != null) 
      { 
       foreach (var fieldItem in SearchFieldList) 
       { 
        //Expression for accessing Fields name property 
        Expression columnNameProperty = Expression.Property(pe, fieldItem.Name); 


        //the name constant to match 
        Expression columnValue = Expression.Constant(fieldItem.Value); 

        //the first expression: PatientantLastName = ? 
        Expression e1 = Expression.Equal(columnNameProperty, columnValue); 

        if (combined == null) 
        { 
         combined = e1; 
        } 
        else 
        { 
         combined = Expression.And(combined, e1); 
        } 
       } 
      } 

      //create and return the predicate 
      if (combined != null) return Expression.Lambda<Func<T, Boolean>>(combined, pe); 
      return null; 
     } 

    } 

,並使用它像這樣:

var lst = _efmodel.Count(2015).AsQueryable() 
            .Where(
      FilterLinq<PazTedad_Result>.GetWherePredicate(
      new SearchField("FieldName", "FieldValue"))).ToList(); 
相關問題