Entity Framework - Mapping Many to Many Relationships
I am struggling on how to map these two tables together, the Column TitleID
on the Name
table maps to the TitleID
on the Title
table. The table primary keys are NameTableID
/ TitleTableID
and are unique, NameID
, TitleID
(on both tables) are not unique, the current record is found by a null in the DateEnd
column.
public class Name
{
public int NameTableID { get; set; }
public int NameID { get; set; }
public int TitleID { get; set; } // Maps to Title.TitleID
public virtual Title Title { get; set; }
public string GivenName { get; set; }
public string FamilyName { get; set; }
public DateTime DateStart { get; set; }
public DateTime? DateEnd { get; set; }
}
public class Title
{
public int TitleTableID { get; set; }
public int TitleID { get; set; } 开发者_运维知识库 // Maps to Name.TitleID
public string Description { get; set; }
public DateTime DateStart { get; set; }
public DateTime? DateEnd { get; set; }
}
I am assuming I need to add a bit of code to OnModelCreating
in my DB Context class, but am struggling with the mapping / code, any ideas?
Thanks, Martin
This is not relation at all. You cannot build relation on two arbitrary columns. You should read some introduction about how database relations work and what are requirements to build a relation.
In many-to-many you must choose unique key on both ends and there must be junction table which will build pairs of related keys. EF doesn't support unique keys so the only way how to build many-to-many relation is on top of primary keys: If you want many-to-many relation you must build it on Title.TitleTableID
and Name.NameTableID
.
精彩评论