EF核心中缺少System.Data.Entity.ModelConfiguration

时间:2016-10-25 08:07:31

标签: entity-framework-core ef-fluent-api .net-core

尝试在OnModelCreating for Entity框架核心上动态加载所有配置。 如果缺少ModelConfiguration,那么另一种方法是什么。

2 个答案:

答案 0 :(得分:4)

现在在Core 2.0中更容易

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();

        }
    }
}

然后在你的数据库上下文中:

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

答案 1 :(得分:3)

当我自己寻找答案时,我偶然发现了这个问题。我发现它不是(但是?)在EF Core中实现,但可以很容易地自己实现。

您可以创建其中一个:

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>());
        }
    }
}

然后您可以为实体本身创建配置: -

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

然后您可以在某处加载所有配置(这可能是更好的方式和更好的地方......但这就是我所做的): -

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());
        }
    }
}