System.Data.Entity.ModelConfiguration missing in EF core

An attempt to load all configurations dynamically into the OnModelCreating for Entity kernel. what happens if ModelConfiguration is missing.

+6
source share
2 answers

I just stumbled upon this question as I was looking for the answer. I found that it is not (yet?) Implemented in EF Core, but can be implemented quite easily.

You can create one of them:

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 } } } 

Then you can download all your configurations somewhere (maybe the best way and the best place for this ... 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()); } } } 
+2
source

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.. } 
0
source

Source: https://habr.com/ru/post/1011679/


All Articles