Dynamically Adding DbSet Properties in DbContext for Entity Framework Code First

When working with Entity Framework Code First, the general pattern to add DbSet properties to the DbContext object is as follows. The Entity Framework will build the model according to the DbSet properties defined in the DbContext.

public class MyAppContext : DbContext

    {

        DbSet<Customer> customers { get; set; }

    }

However, for a project with even a fair bit of domain complexity, defining DbSet properties for all entities would not be possible and we need a way to dynamically read our Entity Types and add them dynamically in the DbContext. This can be achieved by implementing OnModelCreating method of the DbContext. The Entity Types can be read from either the executing assembly Assembly.GetExecutingAssembly() or by loading more than one assemblies which can be placed in a configuration file (as shown below in the example). For details about setting up the custom configuration section with your assemblies see my last post

The following code will add all Class Types to the DbContext for all the assemblies added in the configuration file, notice we are actually calling modelBuilder.Entity<T>() method through reflection.

 

public class MyAppContext : DbContext

    {

        protected override void OnModelCreating(DbModelBuilder modelBuilder)

        {

            CustomAssemblySection configSection = (CustomAssemblySection)System.Configuration.ConfigurationManager.GetSection("CustomAssemblySection");

 

            foreach (CustomAssembly customAssembly in configSection.Assemblies)

            {

                Assembly assembly = Assembly.Load(customAssembly.Name);

                foreach (Type type in assembly.ExportedTypes)

                {

                    if (type.IsClass)

                    {

                        MethodInfo method = modelBuilder.GetType().GetMethod("Entity");

                        method = method.MakeGenericMethod(new Type[] { type });

                        method.Invoke(modelBuilder, null);

                    }

                }

            }

            base.OnModelCreating(modelBuilder);

        }

    }

7 thoughts on “Dynamically Adding DbSet Properties in DbContext for Entity Framework Code First

  1. Just did it with SQLite Code First for use with MEF/Repository Pattern and can’t really believe it.

    You really made my day, night and afternoon!

    Best regards,
    Panos.

  2. Hi, By running your code i will get the next error
    EntityType: EntitySet ‘CAContexts’ is based on type ‘CAContext’ that has no keys defined.\r\n”}.
    [Key] id is also ok ! Any idea where the problem is coming?

  3. Can you please help me to understand this line:
    foreach (CustomAssembly customAssembly in configSection.Assemblies)

    Where is this class CustomAssembly?

Leave a comment