Querying data using Entity Framework from dynamically created table

前端 未结 2 1740
孤独总比滥情好
孤独总比滥情好 2020-12-01 13:40

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

相关标签:
2条回答
  • 2020-12-01 14:12

    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.

    0 讨论(0)
  • 2020-12-01 14:13

    Try this; :)

    string tableName = "MyTableTest";
    
    // Fetch the table records dynamically
    var tableData = ctx.GetType()
                    .GetProperty(tableName)
                    .GetValue(ctx, null);
    
    0 讨论(0)
提交回复
热议问题