NHibernate.PropertyAccessException未处理

时间:2012-11-20 07:08:58

标签: nhibernate fluent-nhibernate nhibernate-mapping fluent-nhibernate-mapping

我是NHibernate的新手。刚开始学习NHibernate。

我使用C#代码

获取运行时错误

NHibernate.PropertyAccessException未处理

 Message=Invalid Cast (check your mapping for property type mismatches); setter of NHibernateDemo.Customer
 InnerException: System.InvalidCastException
     Message=Unable to cast object of type 'NHibernate.Collection.Generic.PersistentGenericSet`1[NHibernateDemo.Order]' to type 'System.Collections.Generic.ISet`1[NHibernateDemo.Order]'.

以下是我为

编写的C#代码
public class Customer {
    public Customer()
    {
        MemberSince = DateTime.UtcNow;
        Orders = new HashSet<Order>();
    }

    public virtual Guid Id { get; set; }
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }

    public virtual Location Address { get; set; }

    public virtual ISet<Order> Orders { get; set; } 
}

这是hbm文件如下

<class name="Customer" table="Customer" lazy="true" >
    <id name="Id">
        <generator class="guid.comb" />
    </id>
    <property name="FirstName" />
    <property name="LastName" />

    <component name="Address" >
      <property name="Street" />
      <property name="City" />
      <property name="State" />
      <property name="Country" />
    </component>

    <set name="Orders" table="`Order`" order-by="Ordered desc">
        <key column="CustomerId" />
        <one-to-many class="Order" />
    </set>
</class>

public class Order {
    public virtual Guid Id { get; set; }
    public virtual DateTime Ordered { get; set; }
    public virtual DateTime Shipped { get; set; }
    public virtual Location ShipAddress { get; set; }

    public virtual Customer Customer { get; set; }
}


<class name="Order" table="`Order`">
    <id name="Id">
        <generator class="guid.comb" />
    </id>
    <property name="Ordered" />
    <property name="Shipped" />

    <component name="ShipAddress" >
        <property name="Street" />
        <property name="City" />
        <property name="State" />
        <property name="Country" />
    </component>

    <many-to-one name="Customer" column="CustomerId" />

</class>

如果我在Customer HBM文件中将“set”部分更改为“list”,并在Customer类中进行必要的更改。程序运行正常。此外,如果我从客户HBM文件中删除“设置”部分;它正在发挥作用。

您能帮我找一下客户HBM文件的“设置”部分有什么问题吗?

1 个答案:

答案 0 :(得分:2)

您的映射几乎是正确的,但ISet接口不是来自System命名空间,而是来自iesi库(与NHibernate一起分发) 因此,您可以参考iesi并更改您的映射:

public virtual Iesi.Collections.Generic.ISet<Order> Orders { get; set; }

或使用IList<>

并使用bag

进行映射
<bag name="Orders" table="`Order`" order-by="Ordered desc">
  <key column="CustomerId" />
  <one-to-many class="Order" />
</bag>

注意也不要忘记初始化列表,以防该实体是通过new运算符创建的,而不是由NHibernate加载