NHibernate: use of IEnumerable as collection type results in error

时光怂恿深爱的人放手 提交于 2019-12-11 09:55:37

问题


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; } }
  }

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; } }
  }

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

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?

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


回答1:


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> works fine when mapping manually or with XML.



来源:https://stackoverflow.com/questions/4028098/nhibernate-use-of-ienumerable-as-collection-type-results-in-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!