Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic table name with entity framework

I have many tables with the same model structure but with other table names with other data (in this case will be ~100 tables). I want to dynamically switch table name in runtime using Entity Framework (for example get name table from routing). Tables in database are dynamically adding and deleting by other script. There is a way to do this with good performance like this?

db.Table("TableName")<SpecificModel>.Where(x => x.ID == ID)
like image 843
Obin Avatar asked Jun 24 '15 19:06

Obin


2 Answers

Do you want to do like this?

foreach (string tableName in new[] { "Table1", "Table2" })
{
   var result = dbContext.Database.SqlQuery<SpecificModel>(string.Format("SELECT * FROM {0} WHERE ID=@p0", tableName), 1).FirstOrDefault();
}
like image 50
Palanikumar Avatar answered Sep 24 '22 21:09

Palanikumar


I did something like this. http://nodogmablog.bryanhogan.net/2013/08/entity-framework-in-an-dynamics-nav-navision-envirnoment/

I had tables which were identical, but they had different names. For example, a customer table but with different prefixes for different companies.

[ACME$Customer] 
[SuperCorp$Customer]

I ended up using dynamic compilation. It's a pretty detailed blog post so I won't go into it here.

like image 36
Bryan Avatar answered Sep 21 '22 21:09

Bryan