0
我有一个自定义集合,它包装了一个.net HashSet并实现了ICollection,然后将其映射为一个集合。我这样做是为了希望NHib能够使用ICollection接口的方式来使用仅仅使用.net HashSet的方式,而不是NHib内部使用的Iesi接口。NHibernate自定义集合不会水合
保存到数据库似乎工作正常,但我得到的异常时,保湿让我知道我需要做的更多:
Unable to cast object of type 'NHibernate.Collection.Generic.PersistentGenericSet`1[ContactMechanisms.Domain.Emails.Email]' to type 'ContactMechanisms.Domain.Emails.EmailCollection'.
These articles常常被视为方法来处理自定义集合处理,但链接被破坏,我可以看到更多的与查询扩展集合。
我必须使用IUserCollectionType吗?如果有的话,任何人都有链接显示示例实施?我在当前的代码/映射中是否有一些愚蠢的行为?
什么是一个好的解决方案?
CODE(父实体片断)
public class Contact : RoleEntity<Party>, IHaveContactMechanisms
{
private readonly ICollection<Email> _emails = new EmailCollection();
public virtual EmailCollection Emails { get { return (EmailCollection) _emails; } }
}
CODE(自定义集合片段)
public class EmailCollection : ContactMechanismSet<Email> { .... }
public class ContactMechanismSet<T> : ValueObject, ICollection<T> where T : ContactMechanism
{
private readonly HashSet<T> _set = new HashSet<T>();
}
MAPPING(HBM值类型集合)
<set name ="_emails" table="Emails" access="field">
<key column="ContactId"></key>
<composite-element class="ContactMechanisms.Domain.Emails.Email, ContactMechanisms.Domain">
<property name="IsPrimary" />
<property name="Address" length="100"/>
<property name="DisplayName" length="50"/>
</composite-element>
</set>
* UPDATE *
这样做在我的对象二传手的作品,但 - 我可以做得更好吗?
public virtual EmailCollection Emails {
get {
if (!(_emails is EmailCollection)) {
// NHibernate is giving us an enumerable collection
// of emails but doesn't know how to turn that into
// the custom collection we really want
//
_emails = new EmailCollection (_emails);
}
return (EmailCollection) _emails ;
}
}
是有可能在EmailCollection实现中使用'ISet'而不是'HashSet '? –
Firo