避免大量if - else检查 - 使用实体框架从字符串中选择表

时间:2013-06-09 11:52:31

标签: c# entity-framework

我正在使用Entity Framework开发应用程序。 我有一个组合框,其中包含数据库中表的名称。 我有以下代码:

string table = cbTables.SelectedItem.ToString();
using (var dbContext = new Entities()) {
    if (table.Equals("Person")) {
        List<Person> list = (from l in dbContext.People select l).ToList();
    } else if (table.Equals("Student")) {
        List<Student> list = (from u in dbContext.Student select u).ToList();
    } else if (table.Equals("Grade")) {
        List<Grade> list = (from p in dbContext.Grade select p).ToList();
}

我怎样才能避免所有这些if-else检查? 是否可以从包含名称的字符串中获取类的名称?

示例:

string = "Person";
var str = //something
List<str> list = (from u in dbContext.str select u).ToList();

4 个答案:

答案 0 :(得分:2)

ComboBox能够通过数据源显示字典,因此您可以将显示文本与实际需要的数据绑定,而不是检查显示文本。然后在这种情况下,我们将它绑定到实体的类型:

Dictionary<string,Type> typeMap = new Dictionary<string,Type> {
    { "Person", typeof(Person) },
    { "Student", typeof(Student) },
    { "Grade", typeof(Grade) },
}

然后将其绑定到ComboBox,如:

cbTables.DataSource = new BindingSource(typeMap, null);
cbTables.DisplayMember = "Key";
cbTables.ValueMember = "Value";

然后,当您需要获得所选实体时,请使用

Type entityType = (Type) cbTables.SelectedValue;
DbSet set = dbContext.Set(entityType);

但是,在此之后,您需要检查entityType并相应地显示表单。如果您的表单需要List,例如列表,然后使用

List<Student> studentList = set.Cast<Student>.ToList();

答案 1 :(得分:1)

假设你不想要一个开关,但你想要一些动态的东西,你可以改用查询:

using (var context = new Context())
{
    var people = context.Database.SqlQuery<Object>(
                       "select * from People").ToList();
}

答案 2 :(得分:1)

扩展我的评论:

您可以声明一个字典,从您的表名字符串映射到您的表格的实际DbSet:

string table = cbTables.SelectedItem.ToString();
using (var dbContext = new Entities()) {
    Dictionary<string, DbSet> mapping = new Dictionary<string, DbSet> {
        { "Person", dbContext.Person },
        { "Student", dbContext.Student },
        { "Grade", dbContext.Grade }
    };

    //...

问题仍然存在 - 如何处理结果集?现在您已经键入了包含每个表成员的特定类型的列表;如果没有某种决定(if / switch),你将无法做到这一点。

答案 3 :(得分:0)

为什么不将Switch用于此目的?

string table = cbTables.SelectedItem.ToString();

using (var dbContext = new Entities()) 
{
    switch (table)
    {
        case"Person":
            List<Person> list = (from l in dbContext.People select l).ToList();
            break;
        case"Student":
            List<Student> list = (from u in dbContext.Student select u).ToList();
            break;
        case"Grade":
            List<Grade> list = (from p in dbContext.Grade select p).ToList();
            break;
    }
}