NHibernate:将IEnumerable用作集合类型会导致错误 [英] NHibernate: use of IEnumerable as collection type results in error

查看:84
本文介绍了NHibernate:将IEnumerable用作集合类型会导致错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用ISet作为收集类型的类,如下所示:

I have a class which uses an ISet as a collection type as below:

  public class Client
  {
    private ISet<Contact> _contacts = new HashedSet<Contact>();
    public virtual ISet<Contact> Contacts { get { return _contacts; } }
  }

我不希望集合本身可以在外部进行修改.但是,如果我将属性的类型更改为IEnumerable,如下所示:

I don't want the collection itself to be able to be modified externally. However, if I change the property's type to IEnumerable as below:

  public class Client
  {
    private ISet<Contact> _contacts = new HashedSet<Contact>();
    public virtual IEnumerable<Contact> Contacts { get { return _contacts; } }
  }

然后,每当我尝试使用此类时,都会出现NHibernate错误:

Then whenever I try to use this class I get the NHibernate error:

System.InvalidCastException:无法转换类型为"NHibernate.Collection.Generic.PersistentGenericBag 1[Kctc.BusinessLayer.ProbateAssist.Entities.Contact]' to type 'Iesi.Collections.Generic.ISet 1 [Kctc.BusinessLayer.ProbateAssist.Entities.Contact]"的对象.

System.InvalidCastException: Unable to cast object of type 'NHibernate.Collection.Generic.PersistentGenericBag1[Kctc.BusinessLayer.ProbateAssist.Entities.Contact]' to type 'Iesi.Collections.Generic.ISet1[Kctc.BusinessLayer.ProbateAssist.Entities.Contact]'.

有什么作用?如何使收藏集的公开版本为只读?

What gives? How can I make the public version of the collection read only?

请注意,我也尝试使用ReadOnlyCollection,并得到相同的错误.

NB I've also tried to use ReadOnlyCollection, and get the same error.

推荐答案

您可能正在使用Fluent自动映射,它会根据接口类型猜测类型为Bag而不是Set.在这种情况下,您将不得不覆盖它.

You are probably using Fluent automapping, which is guessing the type as Bag instead of Set based on the interface type. You'll have to override it in that case.

IEnumerable<T>在手动或使用XML映射时工作正常.

IEnumerable<T> works fine when mapping manually or with XML.

这篇关于NHibernate:将IEnumerable用作集合类型会导致错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆