NHibernate可以使用的只读集合属性

NHibernate可以使用的只读集合属性,nhibernate,collections,fluent-nhibernate,readonly-collection,Nhibernate,Collections,Fluent Nhibernate,Readonly Collection,我的域类具有如下所示的集合: private List<Foo> _foos = new List<Foo>(); public virtual ReadOnlyCollection<Foo> Foos { get { return _foos.AsReadOnly(); } } 现在,当我尝试使用此集合时,我得到: 无法将类型为“NHibernate.Collection.Generic.PersistentGenericBag1[Foo]”的对象强制转换

我的域类具有如下所示的集合:

private List<Foo> _foos = new List<Foo>();
public virtual ReadOnlyCollection<Foo> Foos { get { return _foos.AsReadOnly(); } }
现在,当我尝试使用此集合时,我得到:

无法将类型为“NHibernate.Collection.Generic.PersistentGenericBag
1[Foo]”的对象强制转换为类型为“System.Collections.Generic.List
1[Foo]”

根据,这是因为集合需要作为接口公开给NHibernate,以便NHibernate可以注入它自己的一个集合类

本文建议改用IList,但遗憾的是,这个接口没有包含AsReadOnly()方法,这打乱了我只向外界公开只读集合的计划

有人能建议我可以使用什么样的界面,一种满足相同要求的不同方法,或者一种不涉及这么多挫折的替代职业吗

谢谢

David

AsReadOnly()方法不是获取只读集合的唯一方法

private IList<Foo> _foos = new List<Foo>();
public virtual ReadOnlyCollection<Foo> Foos { get { return new ReadOnlyCollection<Foo>(_foos); } }
private IList\u foos=new List();
公共虚拟只读集合Foos{get{返回新的只读集合(_Foos);}

另一个问题出现了。

由于IList无法满足您的需求,而且您(幸运的)没有使用自动映射,我会将Foos设置为受保护/私有的IList“NHibernate友好”集合,然后创建一个公共只读集合来读取Foos

比如:

    protected IList<Foo> MappableFoos { get; set; }
    public ReadOnlyCollection<Foo> ReadOnlyFoos { get { return new ReadOnlyCollection<Foo>(MappableFoos) } }

    // Mapping file
    HasMany(x => x.MappableFoos ).KeyColumn("ParentClassId").Cascade.All().Inverse().Access.CamelCaseField(Prefix.Underscore);
受保护的IList映射对象{get;set;}
public ReadOnlyCollection ReadOnlyFoos{get{return new ReadOnlyCollection(MappableFoos)}
//映射文件
HasMany(x=>x.MappableFoos).KeyColumn(“ParentClassId”).Cascade.All().Inverse().Access.CamelCaseField(前缀.下划线);

这样,唯一公开的属性就是我可笑地称之为“ReadOnlyFoos

您的答案是一个很好的解决方案,但我只是将集合公开为
IEnumerable
。这种方法的风险很小,因为这些都可以追溯到IList。这是否是可接受的风险取决于应用程序。

考虑将集合公开为
IEnumerable
,而不是
ReadOnlyCollection
;它本质上为您提供了相同级别的保护,而无需将您的模型绑定到特定的集合实现。有关进一步讨论,请参阅。

谢谢Rafael。这是一个我没有想到的有趣的方法。我应该指出的是,在映射汽车物业的备份字段时,需要使用不同的访问策略。谢谢提醒。另一个用户在前一个线程中向我指出了IEnumerable,但我发现将集合公开为IEnumerable太有限了-没有计数属性,没有随机访问,没有包含等。使用System.Linq添加
,您将获得IEnumerable扩展方法提供的几乎所有功能。我有一个字符串列表,它仍然会给我与上述包装相同的错误!
    protected IList<Foo> MappableFoos { get; set; }
    public ReadOnlyCollection<Foo> ReadOnlyFoos { get { return new ReadOnlyCollection<Foo>(MappableFoos) } }

    // Mapping file
    HasMany(x => x.MappableFoos ).KeyColumn("ParentClassId").Cascade.All().Inverse().Access.CamelCaseField(Prefix.Underscore);