Add a column to a many to many relation table code first entity framework

ef-code-first ef-migrations entity-framework-6

Question

I have 2 classes which have a many to many relation.

public class Document
{
    public int Id { get; set; }

    public string Name { get; set; }

    public bool AvailableOffline { get; set; }

    public string URL { get; set; }

    public virtual ICollection<Profile> Profiles { get; set; }

}

public class Profile
{
    public int Id { get; set; }

    public string Name { get; set; }

    public string Description { get; set; }

    public virtual ICollection<Document> Documents { get; set; }
}

On each profile I wish to have a SortOrder field for each document. So I made the joined table explicit in another class

public class ProfileDocuments
{
    [Key, Column(Order = 0)]
    public int DocumentId { get; set; }

    [Key, Column(Order = 1)]
    public int ProfileId { get; set; }

    public int SortOrder { get; set; }

    [ForeignKey("DocumentId")]
    public virtual Document Document { get; set; }

    [ForeignKey("ProfileId")]
    public virtual Profile Profile { get; set; }   
}

But when I update the database the table for this last class will not have a column for SortOrder. It only holds the 2 foreign keys. How can I tell EF to generate this table with my column?

1
0
8/13/2015 9:09:37 AM

Accepted Answer

When a junction table in a many-to-many association should contain more information than just the two foreign keys, it's no longer possible to map the association as a 'pure' many-to-many (with hidden junction class).

You need an explicit class in the class model to address the extra information (as you already found out), but this also changes the association into 1-n-1:

class Document
{
    ...
    public virtual ICollection<ProfileDocument> ProfileDocuments { get; set; }
}

class Profile
{
    ...
    public virtual ICollection<ProfileDocument> ProfileDocuments { get; set; }
}
0
8/13/2015 9:29:32 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow