我想控制我的域名与集合的交互,所以我想我会保护集合并提供一个只读包装,以便内容可见,但我可以确保不直接添加项目到集合。
所以我有以下代码:
public class MyClass
{
public virtual ICollection<Thread> Threads
{
get { return new ReadOnlyWrappedCollection<Thread>(this.ThreadsInternal); }
}
protected virtual ICollection<Thread> ThreadsInternal { get; private set; }
}
我试过了:
this.Map(c => c.Threads)
.Access.None();
结果是MappingException: Could not determine type for: System.Collections.Generic.ICollection'1[[Thread]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, for columns: NHibernate.Mapping.Column(Threads)
我试过了:
this.HasMany(c => c.Threads)
.Access.None();
结果是InvalidOperationException: Tried to add collection 'Threads' when already added
如果我省略了映射,我会得到PropertyNotFoundException: Could not find a setter for property 'Threads' in class 'MyClass'
如何说服NHibernate在映射中忽略此属性?我正在使用Fluent NHibernate,但也请在hbm中发布示例。
答案 0 :(得分:3)
我认为你不能映射ICollection。无论如何,我遵循类似的模式,我发现映射它的最佳方法是映射私有IList。
类别:
public class Invoice
{
private IList<InvoiceItem> _items;
public Invoice()
{
_items = new List<InvoiceItem>();
}
public virtual IEnumerable<InvoiceItem> Items
{
get { return _items; }
}
}
映射:
public class InvoiceMap : ClassMap<Invoice>
{
public InvoiceMap()
{
Table("Invoice");
HasMany(x => x.Items).KeyColumn("InvoiceId")
.Access.CamelCaseField(Prefix.Underscore)
.Cascade.AllDeleteOrphan()
.Inverse()
.AsBag().LazyLoad();
}
}
映射中的关键行是.Access.CamelCaseField(Prefix.Underscore)
,它告诉NHibernate使用私有字段_items。请注意,该集合仍然可以强制转换为IList,但如果需要,您可以将其包装在只读集合中。