9

Trying to load all the configurations dynamically on OnModelCreating for Entity framework core. what is the other way around if ModelConfiguration is missing.

Kenny
  • 819
  • 1
  • 9
  • 24

2 Answers2

6

It's even easier in Core 2.0 now

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace MyApp.DAL.EntityConfigurations
{
    public class StudentConfiguration : IEntityTypeConfiguration<Student>
    {
        public void Configure(EntityTypeBuilder<Student> modelBuilder)
        {

            modelBuilder.Property(f => f.Name).IsRequired();

        }
    }
}

Then in your db context:

public DbSet<Student> Students{ get; set; }

public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);

    // Customizations must go after base.OnModelCreating(builder)

    builder.ApplyConfiguration(new StudentConfig());
    builder.ApplyConfiguration(new SomeOtherConfig());

    // etc.
    // etc..
}
egmfrs
  • 1,272
  • 3
  • 17
  • 31
5

I've just stumbled across this question as I was searching for the answer myself. I found that it is not (yet?) implemented in EF Core but can be implemented yourself fairly easily.

You can create one of these:

using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace Microsoft.EntityFrameworkCore
{
    public abstract class EntityTypeConfiguration<TEntity> where TEntity : class
    {
        public abstract void Map(EntityTypeBuilder<TEntity> modelBuilder);
    }

    public static class ModelBuilderExtensions
    {
        public static void AddConfiguration<TEntity>(this ModelBuilder modelBuilder, EntityTypeConfiguration<TEntity> configuration) where TEntity : class
        {
            configuration.Map(modelBuilder.Entity<TEntity>());
        }
    }
}

And then you can create a configuration for the entity itself: -

using Microsoft.EntityFrameworkCore;
using Project.Domain.Models;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace Project.Persistance.EntityConfigurations
{
    public class MyEntityConfiguration : EntityTypeConfiguration<MyEntity>
    {
        public override void Map(EntityTypeBuilder<MyEntity> modelBuilder)
        {
            modelBuilder
                .Property();//config etc
        }
    }
}

You can then load all your configurations somewhere (there's probably both a better way and a better place for doing it... but this is what I did): -

using Microsoft.EntityFrameworkCore;
using Project.Domain.Models;
using Project.Persistance.EntityConfigurations;

namespace Project.Persistance
{
    public class MyDbContext : DbContext
    {
        // Normal DbContext stuff here

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.AddConfiguration(new MyEntityConfiguration());
        }
    }
}
Jon
  • 190
  • 2
  • 15