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

.net-core ef-fluent-api entity-framework-core

嘗試在OnModelCreating for Entity框架核心上動態加載所有配置。如果缺少ModelConfiguration,那麼另一種方法是什麼。

一般承認的答案

當我自己尋找答案時,我偶然發現了這個問題。我發現它不是(但是?)在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());
        }
    }
}

熱門答案

現在,它在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();

        }
    }
}

然後在你的db上下文中:

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


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因