0

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);
Jason H
  • 4,996
  • 6
  • 27
  • 49

2 Answers2

1

From EF6 onwards you can use:

modelBuilder.HasDefaultSchema(“nameOfDefaultSchema”);
Shiraz Bhaiji
  • 64,065
  • 34
  • 143
  • 252
  • Thanks but this did not solve my problem as I am using schemas to group tables by categories. BUT this is good knowledge to have. – Jason H Jun 21 '15 at 22:31
1

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

x.ToTable("UsersAddresses", "Users");
Gert Arnold
  • 105,341
  • 31
  • 202
  • 291