2

我是 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>

如果我在客户 HBM 文件中将“设置”部分更改为“列表”并在客户类中进行必要的更改。程序运行正常。另外,如果我从客户 HBM 文件中删除“设置”部分;这是工作。

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

4

1 回答 1

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 加载的

于 2012-11-20T07:38:05.253 回答