Changing the Database Schema on a linking table (many-to-many) in EF

61 views Asked by At

I am creating a many to many relationships with my EF Models. The linking table is being created which is fine, but it keeps putting it on the DBO Schema which I do not want. Yes, I could just modify the migration script after its generated but that should be (hoping there is) a way to do this so the schema just works.

From my OnModelCreating Method:

modelBuilder.Entity<AppUser>()
            .HasMany(x => x.Addresses)
            .WithMany(x => x.Users)
            .Map(x => {
                x.ToTable("Users.UsersAddresses");
                x.MapLeftKey("UserId");
                x.MapRightKey("AddressId");
            });

From the Generated Script:

CreateTable(
    "dbo.[Users.UsersAddresses]",
    c => new
        {
            UserId = c.String(nullable: false, maxLength: 128),
            AddressId = c.Long(nullable: false),
        })
    .PrimaryKey(t => new { t.UserId, t.AddressId })
    .ForeignKey("Users.Users", t => t.UserId, cascadeDelete: true)
    .ForeignKey("Users.Addresses", t => t.AddressId, cascadeDelete: true)
    .Index(t => t.UserId)
    .Index(t => t.AddressId);
2

There are 2 answers

1
Gert Arnold On BEST ANSWER

ToTable has an overload in which you can specify the schema name:

x.ToTable("UsersAddresses", "Users");
1
Shiraz Bhaiji On

From EF6 onwards you can use:

modelBuilder.HasDefaultSchema(“nameOfDefaultSchema”);