我希望控制域与集合的交互,因此我认为应该保护该集合,并在其周围提供一个只读包装器,以便内容可见,但我可以确保项不会直接添加到集合中。
所以我有以下代码:
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中发布示例。
发布于 2010-02-25 05:27:47
我不认为你可以映射一个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,但如果需要,可以将其包装在只读集合中。
https://stackoverflow.com/questions/2326141
复制相似问题