I am working in Windows forms application (using Entity Framework) and I have several tables in my database. These tables are similar (they have the same quantity of columns with the same column names), except that they (tables) have different names (it means, I have several entity classes).
On the firstForm (MainForm) I have a listbox, which contains all the table names I have. when the user selects one of them, the new form opens (addForm
). On this form I have several textboxes to fill the table with data.
My problem is that I want to add data to the tables with universal method using Entity Framework. In general, if I have table called Customer
with customerName
and customerAge
columns (and it corresponding class with the same name) I add data to it like this:
using(var context = new MyDbContext())
{
var newCustomer = new Customer {customerName = "Alex", customerAge = "24"};
context.Customers.Add(newCustomer);
context.SaveChanges();
}
I don't want to write the code for every table in my database. I think that, when the item will be selected in the listbox, I have to pass the specific class name to constructor and then transform this name (type of string) into the specific class to add data to the specific table associated with this name.
How I can do this?
Another example - Supplier
table:
using(var context = new MyDbContext())
{
var newSupplier = new Customer { supplierName = "Bob", supplierAge = "20" };
context.Suppliers.Add(newSupplier);
context.SaveChanges();
}