How to add a table to the EF4 Context dynamically in code

We run a series of reports every 6 months and store the results to tables that can be queried/viewed at any time in the future. Depending on the cycle either two or four tables will be added. They have a standard naming convention of yyyy_mmm_Table_x.

Our website is built using ASP.Net MVC2 and the database is modeled using EF4 using the standard model designer, not Code First.

I would like to be able to dynamically add the report tables to the EF4 context at runtime. I don't want to have to manually add them to the model using the designer, otherwise every reporting cycle we have to update and recompile the model just because we added the extra reports. That would be a maintenance headache when nothing else has changed.

I can get a list of the available tables simply by querying sysobjects. If I could get this list and add the tables to the context when the site started up then I could use something like the Dynamic LINQ library to query against them depending on which table the user selected from a dropdown.

I can't use EF4's Code First out of the box because that would force me to create concrete classes for the tables and that would just be the same maintenance headache. I suspect I could use the same strategies the Code First framework uses to dynamically update the context, but I haven't looked at this library at all and I'm hoping someone familiar with it can point me in the right direction.

Otherwise I think I would have to drop back to ADO.Net to handle this area. That may be the best and simple way so I guess I'm looking for comments. I'm not a zealot so I don't need everything to be in LINQ and EF4. :) But it would seem to be a little cleaner and consistent, especially if it allows me to make use of Dynamic LINQ. But sometimes the old way is just simpler.

So, if you have any suggestions or comments I would love to hear them.

Thanks!


Even with common EF you still need new data type for each table because when you map the table you need new ObjectSet of new entity type to be able to run queries. As I know it is not possible to map two tables to the same entity even if table structure is absolutely same.

All runtime mapping is stored in MetadataWorkspace prepared by EntityConnection . So if you want to play with it you can start there but public interfaces of these classes don't look promising.

I guess you want to run Linq-to-entities on these tables so using Stored procedure returning data from correct table based on data parameter is probably not an option.

You should use common ADO.NET for this.

链接地址: http://www.djcxy.com/p/15974.html

上一篇: 首先与型号/数据库

下一篇: 如何在代码中动态添加表格到EF4上下文中