DrAlligieri
DrAlligieri

Reputation: 211

Custom many-to-many mapping with CodeFirst

Start using CodeFirst in my MVC projects and have some trouble. I have in-use database with some predefined schema. There are some tables:

[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

and many-to-many connected table

[QualRef]
[SemID] [bigint] NOT NULL,
[RefID] [bigint] NOT NULL

where SemID referenced to Seminars.ID and RefID referenced to Persons.ID

I'm trying to fix-up my CodeFirst schema binding using configuration class:

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

and register it with this code:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Person>().ToTable("Persons");
        base.OnModelCreating(modelBuilder);
        modelBuilder.Configurations.Add(new PersonConfiguration());
    }

But when I run app using this models error occured - CodeFirst trying to find some table "dbo.People" (?!) and it does not exist (expected). Thank for good answers!

Upvotes: 0

Views: 849

Answers (1)

Jayantha Lal Sirisena
Jayantha Lal Sirisena

Reputation: 21376

Try changing the code like this,

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

//...

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {


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

Upvotes: 1

Related Questions