Dynamic\\ user extensible entities using entity framework

孤街浪徒 提交于 2019-12-06 12:55:29
Michael Petito

I know this question is pretty old, but there's nothing to prevent you from building your EF data model at runtime with whatever your database schema is at that particular moment. Since most of your data model is static, the added complexity is localized to whichever entities can change at runtime:

  1. As you add columns to your database at runtime, so too will you need to add properties to your corresponding type. This means your type is constructed at runtime. Potentially you would create a derived type (or implement some interface) at runtime with the additional properties so that your compile-time code would have a reasonable type to work with otherwise. This can be accomplished using Reflection.Emit.

  2. You'll need to dynamically build your EF mappings at runtime whenever your schema changes. You can do this with EF Code First. If your mappings fit normal EF Code First conventions, there's nothing more you need to do here other than to make sure your runtime types are added to the mapping. Otherwise, you'll have to implement code which determines and configures the necessary mappings for your additional properties at runtime.

  3. Any queries which utilize the additional properties will need to be dynamically constructed at runtime. This means building member access expressions to use in your LINQ queries. Similarly, accessing the values of additional properties only known at runtime would require reflection.

You're correct to be wary of your second approach, which is more widely known as Entity-Attribute-Value (EAV) data modeling. There are a number of downsides to this approach, not the least of which are increased joins / query complexity and lack of foreign key support. However, since the EAV model is declared at compile-time, it is arguably easier to implement.

Alternatively, you might consider using another data store specifically for entities which have a flexible schema, such as document databases.

so each new column will theoretical have to re-map and recompile the DAL project.

You answered your own question :) EF works with fixed database schema, so first option is not an option anyway.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!