Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid a lot of if - else checks - Choose table from string using the entity framework

I'm developing an app with Entity Framework. I've got a combo box with the names of the tables in the database. I have the following code:

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();
}

how can i avoid all these if-else checks? Is it possible to get the name of a class from a string holding the name?

example:

string = "Person";
var str = //something
List<str> list = (from u in dbContext.str select u).ToList();
like image 586
John Matthews Avatar asked Jun 09 '13 11:06

John Matthews


3 Answers

ComboBox is capable of displaying dictionary through the datasource, so you can bind display text with the data you actually want instead of checking the display text. Then in this case we would bind it to the type of the entity:

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

then bind it to ComboBox like:

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

then, when you need to get selected entity, use

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

However, after this you need to inspect entityType and display the form accordingly. If your form needs List e.g. List, then use

List<Student> studentList = set.Cast<Student>.ToList();
like image 59
tia Avatar answered Oct 13 '22 23:10

tia


Assuming you don't want a switch but you want something dynamic, you can use queries instead:

using (var context = new Context())
{
    var people = context.Database.SqlQuery<Object>(
                       "select * from People").ToList();
}
like image 37
Ron Sijm Avatar answered Oct 14 '22 00:10

Ron Sijm


To expand on my comment:

You can declare a dictionary to map from the string of your table name to the actual DbSet that is your table:

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 }
    };

    //...

The problem will remain - what to do with your result set? Right now you have typed lists with the specific type of each table's members; you won't be able to do that without a decision (if/switch) of some sort.

like image 22
sq33G Avatar answered Oct 13 '22 23:10

sq33G