是否可以在 NHibernate 中映射一个使用迭代器的只读属性(即,yield return)?
例如,假设我们有一个Person
具有只读IEnumerable<Cat> Cats
属性的类和一个调用的方法,该方法GetNextCat()
可以获取序列中的下一只猫。
这是可能的映射:
public class PersonMap : ClassMap<Person>
{
public PersonMap()
{
HasMany(x => x.Cats).Access.ReadOnly(); // also tried .AsSet() and .AsBag()
}
}
以下是该属性的两种可能实现IEnumerable<Cat> Cats
:
// fails:
// System.InvalidCastException: Unable to cast object of type '<get_Cats>d__0' to
// type 'System.Collections.Generic.ICollection`1[MyProject.Cat]'.
public virtual IEnumerable<Cat> Cats
{
get
{
var cat = GetNextCat();
while(cat != null)
{
yield return cat;
cat = GetNextCat();
}
yield break;
}
}
// works
public virtual IEnumerable<Cat> Cats
{
get
{
var catList = new List<Cat>();
var cat = GetNextCat();
while(cat != null)
{
catList.Add(cat);
cat = GetNextCat();
}
return catList;
}
}
两个版本的属性产生相同的结果。那么,为什么 NHibernate 与第一个示例不同,而与第二个示例一起使用呢?是不是 NHibernate 只是没有设置来处理编译器生成的类yield return
?或者这只是 Fluent 的问题?