user1943020
user1943020

Reputation:

How do I name a many-many table for EF6 and do I need to add special mapping for this?

I am using EF 6 and trying to map a many to many relationship. So far I have:

public partial class ObjectiveDetail
{
    public ObjectiveDetail()
    {
        this.SubTopics = new List<SubTopic>();
    }
    public int ObjectiveDetailId { get; set; }
    public string Text { get; set; }
    public virtual ICollection<SubTopic> SubTopics { get; set; }
}

public partial class SubTopic
{
    public SubTopic()
    {
        this.ObjectiveDetails = new List<ObjectiveDetail>();
    }
    public int SubTopicId { get; set; }
    public int Number { get; set; }
    public string Name { get; set; }
    public virtual ICollection<ObjectiveDetail> ObjectiveDetails { get; set; }
}

Our DBA is going to write the code for the many to many table. Should this be as follows with a table name of ObjectiveDetailSubTopic or something completely different ?

CREATE TABLE [dbo].[ObjectiveDetailSubTopic] (
    [ObjectiveDetailId] INT NOT NULL,
    [SubTopicId]        INT NOT NULL
);

Can someone tell me if this is the correct way to create the table. Also do I have to add some code to map the ObjectiveDetail and SubTopic classes to the new join class so EF will know what to do?

Upvotes: 2

Views: 1557

Answers (1)

Lin
Lin

Reputation: 15188

Our DBA is going to write the code for the many to many table. Should this be as follows with a table name of ObjectiveDetailSubTopic or something completely different ?

As long as you follow the SQL Database table naming conventions, the table name can be anything. I usually name the join table like yours, by connecting the two table names.

To create the join table using sql, see below:

 CREATE TABLE [dbo].[ObjectiveDetailSubTopic](
        ObjectiveDetailSubTopicId int identity primary key,
        ObjectiveDetailId INT NOT NULL,
        SubTopicId  INT NOT NULL,
        foreign key(ObjectiveDetailId) references ObjectiveDetail(ObjectiveDetailId ),
        foreign key(SubTopicId) references SubTopic(SubTopicId )
    );

But you don't need to create the join table by your own, Entity Framework will create it for you. You just need to mapping the relationship with the Fluent API in your DbContext class like below:

   protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ObjectiveDetail>().
            HasMany(c => c.SubTopics).
            WithMany(p => p.ObjectiveDetails).
            Map(m =>
                    {
                        m.MapLeftKey("ObjectiveDetailId ");
                        m.MapRightKey("SubTopicId ");
                        m.ToTable("ObjectiveDetailSubTopic");
                    });
    }

Upvotes: 4

Related Questions