C# - NHibernate无法将NHibernate.Collection.Generic.PersistentGenericSet强制转换为System.Collections.Generic.IList

rmo*_*bis 5 c# mysql nhibernate

出于某种原因,当我尝试从数据库中获取数据时,NHibernate告诉我它无法转换NHibernate.Collection.Generic.PersistentGenericSet[Ingredient]System.Collection.Generic.IList[Ingredient].这是我的类映射/实现的简化版本:

public class Product {
    protected Product() { };

    public virtual Name { get; set; }
    public virtual IList<Ingredient> {
        get { return new List<Ingredient>(ingredients).AsReadOnly(); }
        protected set { ingredients = value; }
    }

    private IList<Ingredient> ingredients = new List<Ingredient>();
}
Run Code Online (Sandbox Code Playgroud)

-

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
    <class name="LanchesAdmin.Core.Domain.Product, LanchesAdmin.Core" table="product" >
        <id name="ID" generator="identity">
            <column name="id" not-null="true" />
        </id>

        <property name="Name" column="name" length="64" not-null="true" />

        <set name="Ingredients" table="ingredient" fetch="join" lazy="true" inverse="true">
            <key column="product_id" />
            <one-to-many class="LanchesAdmin.Core.Domain.Ingredient, LanchesAdmin.Core" />
        </set>
    </class>
</hibernate-mapping>
Run Code Online (Sandbox Code Playgroud)

我已经看过几个相关的问题,但他们都告诉我使用IList,这正是我正在做的事情.

Dan*_*rth 8

原因是你正在使用一套.并且PersistentGenericSet<T>根本没有实现IList<T>接口.

我认为你应该简单地创建类型的属性IEnumerable<Ingredient>.
这解决了两个问题:

  1. 你摆脱了你提到的错误
  2. 您班级的API直接传达您的班级的消费者不允许通过该属性添加成分.

  • @Raphael_:是的,`ICollection <T>`看起来仍然像用户可以通过这个属性添加项目.相反,`IEnumerable <T>`是一个只读接口.这就是你明确想要的. (3认同)
  • 没关系.您仍然可以将*field*保留为`IList <T>`或`ICollection <T>`. (2认同)