问题
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.ISet
1[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