Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
206 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...