Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change table schema on middle table generated by Entity Framework

I have got model with M:N relation like this:

[Table("Messages", Schema = "public")]
public class Message
{

    public int Id  { get; set; }
    public virtual IList<Phone> Phones{ get; set; }

}

[Table("Phones", Schema = "public")]
public class Phone
{

    public int Id  { get; set; }
    public virtual IList<Message> Messages{ get; set; }

}

So EF generates middle table for me... But default schema of table is not public (it is what i need), but still dbo. And gives me error: schema "dbo" does not exist.

How can I change table schema of MessagePhone table, without creating MessagePhone model class?

like image 997
Alamakanambra Avatar asked Mar 14 '26 07:03

Alamakanambra


1 Answers

I think it is doable. You will have to override OnModelCreating of your DbContext class and configure with fluent API:

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
     modelBuilder.Entity<Message>().HasMany<Phone>(m => m.Phones).WithMany(p => p.Messages).Map
           (
            x =>
               {
                  x.ToTable("MessagePhone", "public");
               }
           );
 }

You will have to test this, not sure i got all of the syntax right.. Don't have VS here to try it.

like image 73
Jurica Smircic Avatar answered Mar 16 '26 20:03

Jurica Smircic