2011-12-02 79 views
2

我有一個方法,爲了綁定數據到網格的目的,需要一個表名稱的字符串值。我一直在爲每個表格手動輸入lambda LINQ表達式,我想將其減少到一行。我怎樣才能給上下文表分配一個變量?LINQ to SQL:將變量分配給數據上下文表?

public void BindDropDown(DropDownList ddl, string tableName) 
    { 
     using (RequisitionModelContainer context = new RequisitionModelContainer()) 
     { 
      var queryReqDepartments = context.ReqDepartments.OrderBy(c => c.Name); 
      var reqDepartment = queryReqDepartments.ToList(); 
      var queryDepartmentCats = context.DepartmentCats.OrderBy(c => c.Name); 
      var departmentCats = queryDepartmentCats.ToList(); 
      var queryTitleCats = context.TitleCats.OrderBy(c => c.Name); 
      var titleCats = queryTitleCats.ToList(); 
      var queryPurposeCats = context.PurposeCats.OrderBy(c => c.Name); 
      var purposeCats = queryPurposeCats.ToList(); 

      //Switch statement takes in a table name and binds table data to the drop down list 
      switch (tableName) 
      {  
       case "ReqDepartments": 
        ddl.DataSource = reqDepartment; 
        BindList(ddl, reqDepartment); 
        break; 
       case "DepartmentCats": 
        ddl.DataSource = departmentCats; 
        BindList(ddl, departmentCats); 
        break; 
       case "TitleCats": 
        ddl.DataSource = titleCats; 
        BindList(ddl, titleCats); 
        break; 
       case "PurposeCats": 
        ddl.DataSource = purposeCats; 
        BindList(ddl, purposeCats); 
        break; 
      } 
     } 
    } 

回答

1

希望這有助於:

private static IDictionary<string,Func<RequisitionModelContainer, IQueryable>> tableProviders; 

public static MyClass() //your class' static constructor 
{ 
    tableProviders = new Dictionary<string,Func<RequisitionModelContainer, IQueryable>> 
    { 
     {"ReqDepartments", context => context.ReqDepartments.OrderBy(c => c.Name)}, 
     {"DepartmentCats", context => context.DepartmentCats.OrderBy(c => c.Name)}, 
     {"TitleCats", context => context.TitleCats.OrderBy(c => c.Name)}, 
     {"PurposeCats", context => context.PurposeCats.OrderBy(c => c.Name)} 
    }; 
} 

public void BindDropDown(DropDownList ddl, string tableName) 
{ 
    using (RequisitionModelContainer context = new RequisitionModelContainer()) 
    { 
     var data = tableProviders[tableName](context); 
     ddl.DataSource = data; 
     BindList(ddl, data); 
    } 
}