2012-12-11 86 views
0

我有一个场景,用户实体有一个国家id的列表,保持为IList。当使用流利NHibernate和AsList()时指定主键

public virtual IList<int> TradeCountries { get; protected set; } 

目前,这被映射为

HasMany(x => x.TradeCountries).Element("TradeCountryId").AsList(x => x.Column("TradeCountryIndex")); 

产生的表的定义如下

create table TradeCountries (
    User_id INT not null, 
    TradeCountryId INT null, 
    TradeCountryIndex INT not null, 
    primary key (User_id, TradeCountryIndex) 
) 

这一切工作正常 - 但我想就TradeCountries的PK是User_id,TradeCountryId。在使用AsList()进行映射时,我似乎无法找到这样做的方法。有任何想法吗?

+0

你想对你的主键由两个领域? (User_id和TradeCounryId) –

+0

为什么要在PK中使用TradeCountryId?唯一性约束? NHibernate使用PK中的索引,因为这对NH来说很重要。你真的需要存储每个contry在集合中的位置吗? –

+0

@OskarBerggren我想把它作为一个列表映射,以避免映射组件时出现的'删除所有/重新插入所有'行为或包 –

回答

3

在功能NHibernate使用集合的转化进入(as described here)这种方式:

// <set> 
public virtual ISet<Child> Children { get; set; }  
HasMany(x => x.Children); // <set /> 

// <bag> 
public virtual IList<Child> Children { get; set; }  
HasMany(x => x.Children); // <bag /> 

// <list> 
public virtual IList<Child> Children { get; set; }  
HasMany(x => x.Children).AsList(...; // <list /> 

实质/被详细描述在文档Understanding Collection performanceAyende's post: <list>)描述这些映射的差异。 提取

...而<set/>是一个无序的集合独特的元素,一个<list/> 是元素的集合,其中为了此事,并重复 元素允许...

换句话说,当使用<list>时,您必须保留索引列上的PK,因为可能有重复。

在你的情况,只是<bag>映射(没有明确.AsList()调用)可能是效率不够高,你可以删除索引列,并移动到PK的关键元素(USER_ID,TradeCountryId)。

注:C#的IList仍然允许有更多的“相同”的元素,你应该检查它的业务层上