I have a requirement in my project to add/delete fields dynamically during runtime. I have created already this feature but not in EF. I want to create this feature using EF. Any ideas how to do this one?
-
EF is not suited for this type of requirements.– ErangaJan 3, 2012 at 10:09
-
What do you mean by 'field'? Do you mean you want to add database columns without having to recompile your project?– StevenJan 3, 2012 at 10:17
-
@Steven-Yes, is there is a possible way to recompile the schema at runtime?– user335160Jan 3, 2012 at 10:21
3 Answers
If you need to have dynamic data structure you must either use completely different architecture or you cannot use EF. EF is not tool for dynamically changing databases - just look how do you work with EF. You map static table to static class definition. If you change table at runtime how do you change the class (no dynamic
support in EF)?
As example of alternative database structure you can use either database with multiple predefined columns of different types and new fields will be mapped to new types. You will have additional layer of "mapping" in your application which will interpret your database content based on some type metadata stored elsewhere. This is approach for example used by Sharepoint (at least 2007) where you have separately stored content type (data description) but all content is in one huge table with large number of columns.
Another example is structure where you have separate table for core data (shared among all entities), separate table for property description and separate table for property values related to core data. This database structure has a name but I cannot recall it at the moment.
Every dynamic approach has its price. Generally you will lose some part of strongly typed work and you will lose performance.
Your linked tool is not for changing database structure. It is just for modification of names in mapping but table structure must remain the same.
-
@Ladislav-is there no way to recompile the schema(edmx) at runtime, once there is any changes in the db? Jan 3, 2012 at 11:04
-
2"Recompiling" model is not enough you need to recompile your code and reload the assembly and it is all very hard because for example once you loaded assembly you cannot unload it - you can only unload
AppDomain
which loaded it. Jan 3, 2012 at 11:38 -
Anyone know the name of the database structure? Is it "Key-Value Store"?– AXMIMJul 12, 2017 at 21:07
-
@AXMIM, I guess Ladislav is talking about entity–attribute–value model. It's certainly not a key-value store.– Roman K.Mar 16, 2021 at 13:35
This is takne verbatin from the Rowan Miller Blog.
http://romiller.com/2012/03/26/dynamically-building-a-model-with-code-first/ .
Still Has to be changed so the properties for the classes are read from some configuration source or from the fields on the database table.
Dynamically Building A Model With Code First Posted on March 26, 2012.
I’ve answered a few emails recently on this topic so it felt like time to turn it into a blog post.
In this scenario the set of classes that make up your model isn’t known at compile time and is discovered dynamically at runtime. An example of such a scenario is a WordPress/Orchard/etc. style website that allows modules to be plugged in. These modules live in a separate assembly and may contain classes that represent data to be persisted in the application database. These classes are all pulled into a central Code First model to be used for data access.
Finding the Classes There are lots of different approaches for identifying the classes to be included in the model. For this example lets use a [Persistent] attribute, something like this:
[AttributeUsage(AttributeTargets.Class)] public class PersistentAttribute : Attribute { } Now we can add some logic to the OnModelCreating method of our context to scan assemblies and add any classes with the [Persist] attribute. We’re going to assume that the assemblies that may contain classes are all loaded into the current AppDomain, of course you may have some other mechanism that provides a list of the assemblies to check.
public class MyContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
var entityMethod = typeof(DbModelBuilder).GetMethod("Entity");
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
var entityTypes = assembly
.GetTypes()
.Where(t =>
t.GetCustomAttributes(typeof(PersistentAttribute), inherit: true)
.Any());
foreach (var type in entityTypes)
{
entityMethod.MakeGenericMethod(type)
.Invoke(modelBuilder, new object[] { });
}
}
}
}
In this example the entire model is dynamically discovered, but you could also have some static parts of the model that are registered with modelBuilder too.
An Alternative Using EntityConfiguration Code First allows you to create a class that derives from EntityTypeConfiguration to encapsulate the Fluent API configuration for an entity. If your using this approach to configuration you can just look for these configuration classes and register them, instead of finding the entities to register. Notice that we are filtering out the EntityFramework assembly since it has some configuration classes that it uses internally.
public class MyContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
var addMethod = typeof(ConfigurationRegistrar)
.GetMethods()
.Single(m =>
m.Name == "Add"
&& m.GetGenericArguments().Any(a => a.Name == "TEntityType"));
foreach (var assembly in AppDomain.CurrentDomain
.GetAssemblies()
.Where(a => a.GetName().Name != "EntityFramework"))
{
var configTypes = assembly
.GetTypes()
.Where(t => t.BaseType != null
&& t.BaseType.IsGenericType
&& t.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));
foreach (var type in configTypes)
{
var entityType = type.BaseType.GetGenericArguments().Single();
var entityConfig = assembly.CreateInstance(type.FullName);
addMethod.MakeGenericMethod(entityType)
.Invoke(modelBuilder.Configurations, new object[] { entityConfig });
}
}
}
}
What if the Model Changes? Code First Migrations to the rescue… You may not be able to use Migrations from the Package Manager Console because the logic to discover your model may require you full application to be running. Fortunately those commands are just thin wrappers over an API. Here is some code to automatically change the database when new classes or properties are added to the model. My recent blog post has more details on invoking Migrations from code.
var config = new DbMigrationsConfiguration<MyContext> { AutomaticMigrationsEnabled = true };
var migrator = new DbMigrator(config);
migrator.Update();
Adding and deleting fields during runtime is not a good idea to start with.
The database structure should be static, as it should reflect your class structure, and your class structure is static, whether you want it or not.
In case you have a dynamic table you there are better was to implement it, for example, have a table with fields "rowID, field, value", and fill in the values this way.
If you really need to add/remove fields to a table at runtime, you can create a stored procedure that adds/deletes the field, and then map the SP with Entity Framework.
This, however, might cause a lot of problems, because Entity Framework will not be able to map/unmap the new/deleted fields, and therefore will crash the moment you try to access the said table.
-
@Svarog-Yes, I have experienced this one, that is why I used another approach. I am trying my luck her in stackoverflow if someone done this before. I don't know if this link efmodeladapter.codeplex.com is applicable to my problem. Jan 3, 2012 at 10:24
-
The Runtime Model Adapter is for adding/removing prefixes and such fine-tunings. You can not change the fields in your classes/tables with it.– SvarogJan 3, 2012 at 10:51