Have a requirement to create instance of Entity Framework generated Model class dynamically by passing table name as parameter (Model generated in DB first approach and using EF 6.0)
like,
// Input Param string tableName // Context always same DBContext dbContext= new DBContext(); //Need to create object query dynamically by passing //table name from front end as below IQueryable<"tableName"> query = dbContext."tableName ";
Need to pass 100+ tables as input param and structure of all table is same.
Please help.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can use a Dictionary. Maybe you want something like this:
// Input Param
string tableName = "TblStudents";
Dictionary<string, Type> myDictionary = new Dictionary<string, Type>()
{
{ "TblStudents", typeof(TblStudent) },
{ "TblTeachers", typeof(TblTeacher) }
};
// Context always same
DBContext dbContext = new DBContext();
DbSet dbSet = dbContext.Set(myDictionary[tableName]);
But you can not use none of the LINQ extension methods because they are defined on the generic type IQueryable<T> but the non-generic overload of DbContext.Set, returns a non-generic DbSet. Also this class implements non generic IQueryable.
You have two option to use LINQ methods here:
-
Add
System.Linq.Dynamicto your project (to installSystem.Linq.Dynamic, run the following command in the Package Manager Console ):Install-Package System.Linq.Dynamic
And then you can:
var dbSet = dbContext.Set(myDictionary[tableName]).Where("Id = @a", 12); -
Use the
Findmethod://But this returns a single instance of your type var dbSet = dbContext.Set(myDictionary[tableName]).Find(12);
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0