NHibernate 和 ReadOnlyCollection
NHibernate 似乎确实不喜欢返回 ReadOnlyCollection,尽管我已经实现了我在大约 30 个地方读到的内容作为支持私有字段的只读集合的正确访问策略。
我的实体中有以下代码:
private readonly IList<TagAlias> _aliases = new List<TagAlias>();
public IEnumerable<TagAlias> Aliases
{
get
{
return new ReadOnlyCollection<TagAlias>(this._aliases);
}
}
以及以下映射以允许访问支持字段
public sealed class TagMap : ClassMap<Tag>
{
public TagMap()
{
Table("Tag");
Id(x => x.Id).Column("TagId").GeneratedBy.Identity();
Map(x => x.Value).Column("TagName");
HasMany(x => x.Aliases)
.AsSet()
.Access.ReadOnlyPropertyThroughCamelCaseField(Prefix.Underscore)
.KeyColumn("TagId")
.LazyLoad()
.Inverse()
.Cascade.AllDeleteOrphan();
}
}
当我执行 .Clear() 之类的操作时,为什么 NHibernate 仍然坚持通过只读集合获取支持列表,而不是访问就像我在映射中告诉它的那样吗?我不愿意仅仅为了持久层而改变我的域模型,但 NHibernate 似乎并不想合作。
我得到的错误是“拥有级联=“all-delete-orphan”的集合不再被拥有的实体实例引用”,但当我在属性 getter 中返回 this._aliases
时,它就消失了。
NHibernate really does not seem to like returning a ReadOnlyCollection, depsite me having implemented what I've read in about 30 places as the correct access strategy for a read only collection backed to a private field.
I have the following code in my entity:
private readonly IList<TagAlias> _aliases = new List<TagAlias>();
public IEnumerable<TagAlias> Aliases
{
get
{
return new ReadOnlyCollection<TagAlias>(this._aliases);
}
}
and the following mapping to allow access to the backing field
public sealed class TagMap : ClassMap<Tag>
{
public TagMap()
{
Table("Tag");
Id(x => x.Id).Column("TagId").GeneratedBy.Identity();
Map(x => x.Value).Column("TagName");
HasMany(x => x.Aliases)
.AsSet()
.Access.ReadOnlyPropertyThroughCamelCaseField(Prefix.Underscore)
.KeyColumn("TagId")
.LazyLoad()
.Inverse()
.Cascade.AllDeleteOrphan();
}
}
Why on earth does NHibernate still insist on getting the backing list via the ready only collection when I do something like .Clear(), rather than accessing it like I have told it to in the mapping? I am loath to change my domain model just for the sake of the persistence layer, but NHibernate just doesn't seem to be wanting to cooperate.
The error I get is "A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance" but it goes away when I just return this._aliases
in the property getter.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我通常使用这样的集合并且没有问题:
我不确定您到底如何使用集合来获得此错误,但我通常在类中为我的集合添加和删除方法。如果这对您没有帮助,也许您可以发布导致该错误的示例。
这是我几个月前发布的相关文章:
将 HasMany 和 ManyToMany 关系公开为 IEnumerable
I generally use collections like this and don't have problems:
I'm not sure of exactly how you are using your collections to get this error but I generally have add and remove methods for my collections inside the classes. If this doesn't help you maybe you could post the example that causes that error.
Here is a related article I posted several months back:
Exposing HasMany and ManyToMany relationships as IEnumerable