Entity framework 使用CodeFirst自定义多对多映射

Entity framework 使用CodeFirst自定义多对多映射,entity-framework,entity-framework-4.1,ef-code-first,Entity Framework,Entity Framework 4.1,Ef Code First,在我的MVC项目中开始使用CodeFirst,会遇到一些麻烦。 我使用了一些预定义模式的数据库。 有一些表格: [Persons] [ID] [bigint] IDENTITY(1,1) NOT NULL, [Name] [nvarchar](30) NOT NULL, [Birthday] [datetime] NOT NULL, [Address] [nvarchar](30) NOT NULL, [Zip] [nvarchar](5) NOT NULL, [City] [nvarchar]

在我的MVC项目中开始使用CodeFirst,会遇到一些麻烦。 我使用了一些预定义模式的数据库。 有一些表格:

[Persons]
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](30) NOT NULL,
[Birthday] [datetime] NOT NULL,
[Address] [nvarchar](30) NOT NULL,
[Zip] [nvarchar](5) NOT NULL,
[City] [nvarchar](30) NOT NULL,
[Tax] [money] NOT NULL,
[Memo] [varbinary](max) NULL

[Seminars]
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](20) NOT NULL
多对多连通表

[QualRef]
[SemID] [bigint] NOT NULL,
[RefID] [bigint] NOT NULL
其中SemID指的是Inspects.ID,RefID指的是Persons.ID

我正在尝试使用配置类修复CodeFirst架构绑定:

class PersonConfiguration : EntityTypeConfiguration<Person>
    {
        internal PersonConfiguration()
        {
            this.HasMany(i => i.Seminars)
                .WithMany(c => c.Persons)
                .Map(mc =>
                {
                    mc.MapLeftKey("SemID");
                    mc.MapRightKey("RefID");
                    mc.ToTable("QualRef");
                });
        }
    }
class PersonConfiguration:EntityTypeConfiguration
{
内部人员配置()
{
这个有很多(i=>i
.有许多人(c=>c.人)
.Map(mc=>
{
MapLeftKey mc(“SemID”);
mc.MapRightKey(“RefID”);
mc.ToTable(“QualRef”);
});
}
}
并使用此代码注册:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Person>().ToTable("Persons");
        base.OnModelCreating(modelBuilder);
        modelBuilder.Configurations.Add(new PersonConfiguration());
    }
模型创建时受保护的覆盖无效(DbModelBuilder modelBuilder)
{
modelBuilder.Entity().ToTable(“人员”);
基于模型创建(modelBuilder);
添加(新PersonConfiguration());
}

但当我使用此模型运行应用程序时,出现了错误-CodeFirst试图查找一些表“dbo.People”(?!),但它不存在(预期)。谢谢你的回答

尝试这样更改代码

class PersonConfiguration : EntityTypeConfiguration<Person>
    {
        public PersonConfiguration()
        {
            ToTable("Persons");

            this.HasMany(i => i.Seminars)
                .WithMany(c => c.Persons)
                .Map(mc =>
                {
                    mc.MapLeftKey("SemID");
                    mc.MapRightKey("RefID");
                    mc.ToTable("QualRef");
                });
        }
    }

问题是ToTable(“人”)没有任何理由。问题是“QualRef”表。您是否尝试过我的代码?尝试更改代码中
OnModelCreating
中的代码顺序,以便在
modelBuilder.Configurations.Add(new PersonConfiguration())之后的末尾调用base方法。是的,贾扬塔,我试过这个。问题是(我认为)EF试图为连接表创建(或关联)新映射。为什么会这样-我不知道。非常感谢你!因为我第一次删除ToTable()(认为问题出在QualRef上)解决方案是错误的。在此之后,我生成DB创建脚本并检查问题是否与人员有关。代码现在运行良好!
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {


            modelBuilder.Configurations.Add(new PersonConfiguration());
            base.OnModelCreating(modelBuilder);
        }