I am using EF5 (Code 1st) and doing all my configurations with the Fluent API. My model looks like this:
public class AddressType
{
public int AddressTypeID { get; set; }
public string Name { get; set; }
}
public class Address
{
public int AddressID { get; set; }
public int StateID { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
public State State { get; set; }
public ICollection<Person> People { get; set; }
}
public class Person
{
public int PersonID { get; set; }
public string Name { get; set; }
public ICollection<Address> Addresses { get; set; }
}
My database contains tables for the above classes + the below Many:Many table:
Person.Person2Address
(
PersonID INT NOT NULL,
AddressID INT NOT NULL,
AddressTypeID INT NOT NULL,
)
The 3 fields above are all foreign keys & the 3 together make up the Primary Key for the table.
Typically my M:M setups only involve 2 fields in the PK. And I would map it like this:
var addressCfg = mb.Entity<Address>();
addressCfg.ToTable("Address", "Geo");
addressCfg.HasMany(a => a.People)
.WithMany(p => p.Addresses)
.Map(mmc =>
{
mmc.ToTable("Person2Address", "Person");
mmc.MapLeftKey("AddressID");
mmc.MapRightKey("PersonID");
});
But I don’t know how to configure this 3rd field in the PK or how CRUD would even work in EF in this case.
Any examples of how this should be handled would be greatly appreciated.
You can’t map this as many-to-many relationship. You need three one-to-many relationships with an intermediate additional entity
Person2Addressthat represents the link table with the three keys. The collections inPersonandAddressmust both refer to this intermediate entity (and optionally also a collection inAddressType).The model would be like this:
And the mapping with Fluent API:
Or use
WithMany(at => at.Person2Addresses)in the last mapping if you want to include the collection inAddressType.