Skip to content Skip to sidebar Skip to footer

Querying Data Using Entity Framework From Dynamically Created Table

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 processes a bulk of information, and

Solution 1:

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.

Solution 2:

Try this; :)

string tableName = "MyTableTest";

// Fetch the table records dynamicallyvar tableData = ctx.GetType()
                .GetProperty(tableName)
                .GetValue(ctx, null);

Post a Comment for "Querying Data Using Entity Framework From Dynamically Created Table"