2011-08-15 156 views
2

我想映射具有多對多關係的Person和Address類。我想將Address集合映射爲IDictionary,並將Address屬性類型作爲鍵。該關係僅從Person一側映射。將多對多關係映射爲IDictionary

public class Person 
{ 
    public IDictionary<int, Address> Addresses { get; set; } 
} 

public class Address 
{ 
    public int Type { get; set; } 
} 

我使用的映射是:

HasManyToMany<Address>(x => x.Addresses).Table("PersonAddress") 
    .ParentKeyColumn("PersonId").ChildKeyColumn("AddressId") 
    .AsMap(x => x.Type); 

的問題是,發出的SQL是:

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 

它試圖從多到許多加盟選擇類型表,它不存在。我嘗試了一些映射的變體,但沒有成功。

如何映射此?

回答

5

這是不可能的。字典在關係表中需要一個關鍵值。您擁有的表格結構是一個簡單的多對多包或一套。

我會做什麼,是它映射爲一個正常的袋子或設置,並提供字典喜歡在實體訪問:

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); 
    } 
} 
+0

令人失望。我最終做了類似於你所建議的事情,而且長期來看它可能是一個更好的解決方案。 –

0

您需要使用的組件:

HasMany<Address>(x => x.Addresses) 
       .AsMap<int>("FieldKey") 
       .Component(x => x.Map(c => c.Id)); 
+0

感謝您的答覆,但這不起作用。生成的SQL是'SELECT addressesd0_.PersonId如PersonId0_, addressesd0_.AddressId如AddressId0_, addressesd0_.Type如Type0_ FROM dbo.PersonAddress addressesd0_ WHERE addressesd0_.PersonId = 420893'。請注意,地址表根本不包含在查詢中。 –