LINQ to SQL:将变量赋给数据上下文表?

时间:2011-12-02 15:38:19

标签: asp.net linq

我有一个方法,它接受表名的字符串值,以便将数据绑定到网格。我一直在手动为每个表键入lambda LINQ表达式,我想将它减少到一行。如何将变量分配给上下文表?

    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 个答案:

答案 0 :(得分: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);
    }
}