Mapping a many-to-many relationship as an IDictionary
I am trying to map a Person and Address class that have a many-to-many relationship. I want to map the Address collection as an IDictionary with the Address property Type as the key. The relationship is only mapped fro开发者_C百科m the Person side.
public class Person
{
public IDictionary<int, Address> Addresses { get; set; }
}
public class Address
{
public int Type { get; set; }
}
The mapping I am using is:
HasManyToMany<Address>(x => x.Addresses).Table("PersonAddress")
.ParentKeyColumn("PersonId").ChildKeyColumn("AddressId")
.AsMap(x => x.Type);
The problem is that the SQL issued is:
SELECT addressesd0_.PersonId as PersonId1_,
addressesd0_.AddressId as AddressId1_,
addressesd0_.Type as Type1_,
address1_.AddressId as AddressId5_0_
-- etc.
FROM dbo.PersonAddress addressesd0_
left outer join dbo.Address address1_
on addressesd0_.AddressId = address1_.AddressId
WHERE addressesd0_.PersonId = 420893
It's attempting to select Type from the many-to-many join table, which doesn't exist. I've tried a number of variations of the mapping without success.
How can I map this?
It's not possible. Dictionaries need a key value in the relational table. The table structure you have is a simple many-to-many bag or set.
What I would do, is map it as a normal bag or set and provide dictionary like access in the entity:
public class Person
{
private IList<Address> addresses;
public IEnumerable<Address> Addresses { get { return addresses; } }
public Address GetAddressOfType(int addressType)
{
return addresses.FirstOrDefault(x => x.Type == addressType);
}
public void SetAddress(Address address)
{
var existing = GetAddressOfType(address.Type);
if (existing != null)
{
addresses.Remove(existing);
}
addresses.Add(address);
}
}
You need to use components:
HasMany<Address>(x => x.Addresses)
.AsMap<int>("FieldKey")
.Component(x => x.Map(c => c.Id));
精彩评论