2011-08-09 138 views
0

我有一個Users表和Profiles表。一個用戶可以有多個配置文件,一個配置文件可以有很多用戶。另外一個要求是用戶的配置文件在保存到數據庫時應該保持它們的指定順序。因此,我有以下關係:NHibernate映射多對多具體順序

tables

我怎樣才能正確映射這班與NHibernate?是唯一的方法來創建另一個類如UserProfile具有Order屬性,並參考UserProfile?這是否有一個更光滑的技術?我想避免這種情況,因爲它會添加另一個不一定需要的抽象層。

感謝您的任何建議。

回答

1

我實際上發現了正確的方式來解決這個問題。

FluentMappings映射應該使用AsMap(indexColumnName)<map name="Profiles"><index column="Order" type="integer" /></map>

// Inside the UserMapping (or an AutoMappingOverride). 
this.ManyToMany(u => u.Profiles).AsMap("`Order`"); // "Order" is the column we want! 

// Which produces this SQL - SQLite in my case: 
create table ProfileToUser (
    User_id INT not null, 
    Profile_id INT not null, 
    "Order" INT not null,   // Exactly what I wanted. 
    primary key (User_id, Order)) 
1

我已經看到了這個問題問了幾次,我不認爲我已經看到了巨大的解決無需創建用戶配置實體。

你可以做的一件事就是隻在Users或Profiles類中引用這個實體。

public virtual AddProfile(Profile profileToAdd, int order) 
{ 
    //Create middle man object 
    UserProfile newUserProfile = new UserProfile(this.Id, profileToAdd, order); 
    this.UserProfiles.Add(newUserProfile); 
} 

這可能不是你的情況完美的,但如果你想摘要:中間人遠,這樣你只對付它:添加新的配置文件到用戶時,你可以做這樣的事情,例如在你的實體中,我認爲上面的例子給你一個開始。

+0

謝謝!這使我朝着正確的方向前進! – TheCloudlessSky

+0

我希望你不介意,但我會改變我的答案作爲接受的答案,因爲它直接使用NH來解決這個問題!希望這也能幫助你:)。 – TheCloudlessSky