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();
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();
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();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With