TLDR; How do I read data from a table using Entity Framework, when the table name isn\'t known at compile-time?
There is an external system that pro
It is not directly possible. When you map entity to ResultTableTemplate
you hardcode the name of the table for this entity. Entities can be mapped only once (per model) so at runtime every EF query for this entity always results in query to ResultTableTemplate
table.
The only way to change is behavior is modifying mapping file (SSDL) at runtime which is quite ugly hack because it requires you to change XML file and reload it. You will have to build MetadataWorkspace
manually every time you change the file. Building MetadataWorkspace
is one of the most performance consuming operation in EF. In the normal run MetadataWorkspace
is created only once per application run.
There is simple workaround. You know the table name and you know the table structure - it is fixed. So use direct SQL and use EF to materialize the result into your mapped entity class:
var table = context.ExecuteStoreQuery<ResultTableTemplate>("SELECT ... FROM " + tableName);
The disadvantage is that you cannot use Linq in this approach but your requirement is not very well suited for EF.
Try this; :)
string tableName = "MyTableTest";
// Fetch the table records dynamically
var tableData = ctx.GetType()
.GetProperty(tableName)
.GetValue(ctx, null);