Dynamically Instantiate Model object in Entity Framework DB first by passing type as parameter

前端 未结 1 892
别那么骄傲
别那么骄傲 2020-12-03 12:37

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 usin

相关标签:
1条回答
  • 2020-12-03 13:35

    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:

    1. Add System.Linq.Dynamic to your project (to install System.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);
      
    2. Use the Find method:

      //But this returns a single instance of your type
      var dbSet = dbContext.Set(myDictionary[tableName]).Find(12);
      
    0 讨论(0)
提交回复
热议问题