【问题标题】:NHibernate Many-to-Many Domain Object PropertiesNHibernate 多对多域对象属性
【发布时间】:2009-10-15 20:42:57
【问题描述】:

我刚开始使用 NHibernate。我使用 Products 和 Suppliers 设置了一个简单的多对多场景,如下所示:

<class name="Product" table="Products">
    <id name="Id">
      <generator class="guid" />
    </id>
    <property name="Name" />

    <bag name="SuppliedBy" table="ProductSuppliers" lazy="true">
      <key column="ProductId" foreign-key="FK_ProductSuppliers_ProductId" />
      <many-to-many column="SupplierId" class="Supplier" />
    </bag>
</class>

<class name="Supplier" table="Suppliers">
    <id name="Id">
      <generator class="guid" />
    </id>
    <property name="Name" />

    <bag name="Products" table="ProductSuppliers" lazy="true" inverse="true">
      <key column="SupplierId"  foreign-key="FK_ProductSuppliers_SupplierId" />
      <many-to-many column="ProductId" class="Product" />
    </bag>
</class>

我现在正在尝试将包连接到我的域对象。通过阅读我提出的文档(使用 Iesi.Collections lib):

'In Product
Private _Suppliers As ISet = New HashedSet()
Public Overridable Property SuppliedBy() As HashedSet
    Get
        Return _Suppliers
    End Get
    Set(ByVal value As HashedSet)
        _Suppliers = value
    End Set
End Property

'In Supplier
Private _Products As ISet = New HashedSet()
Public Overridable Property Products() As HashedSet
    Get
        Return _Products
    End Get
    Set(ByVal value As HashedSet)
        _Products = value
    End Set
End Property

但是,当我尝试将供应商添加到产品并调用 save 时,我收到以下错误

无法将“NHibernate.Collection.PersistentBag”类型的对象转换为“Iesi.Collections.HashedSet”类型

我尝试过使用各种类型,例如 ICollection 和 List(Of T),但我不断收到相同的错误。

无法转换类型为“NHibernate.Collection.Generic.PersistentGenericBag1[Domain.Supplier]' to type 'System.Collections.Generic.List1[Domain.Supplier]”的对象

我在这里错过了什么?

【问题讨论】:

    标签: .net nhibernate


    【解决方案1】:

    文档讨论了使用 IList 或 IList(of Entity) 创建包并使用 List 或 List(of Entity) 构造它。 (NHibernate 1.2 参考的第 6.2 节)。

    bag 的语义与 Set 的语义不匹配,即 Set 只能有唯一的实例,而 bag 可以有重复的实例。作为一个公平的评论,列表也不完全匹配包的语义(包没有索引),但对于 NHibernate 来说已经足够接近了。

    然后您的集合映射应该是(使用泛型 - 取出(供应商)以删除泛型:

    'In Product
    Private _Suppliers As IList(of Supplier) = New List(of Supplier)
    Public Overridable Property SuppliedBy() As IList(of Supplier)
        Get
            Return _Suppliers
        End Get
        Set(ByVal value As IList(of Supplier))
            _Suppliers = value
        End Set
    End Property
    

    【讨论】:

    • 非常感谢!完美运行
    【解决方案2】:

    公共属性Supplier.Products 需要是ISetISet(Of Product) 类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-13
      • 1970-01-01
      相关资源
      最近更新 更多