簡體   English   中英

NHibernate映射問題

[英]NHibernate Mapping problem

我的數據庫由NHibernate映射文件驅動。

我有一個Category類,如下所示:

public class Category {

        public Category() : this("") { }

        public Category(string name) {
            Name = name;
            SubCategories = new List<Category>();
            Products = new HashSet<Product>();
        }


        public virtual int ID { get; set; }
        public virtual string Name { get; set; }
        public virtual string Description { get; set; }
        public virtual Category Parent { get; set; }
        public virtual bool IsDefault { get; set; }
        public virtual ICollection<Category> SubCategories { get; set; }
        public virtual ICollection<Product> Products { get; set; }   

這是我的映射文件:

<property name="Name" column="Name" type="string" not-null="true"/>
<property name="IsDefault" column="IsDefault" type="boolean" not-null="true" />
<property name="Description" column="Description" type="string" not-null="true" />

<many-to-one name="Parent" column="ParentID"></many-to-one>

<bag name="SubCategories" inverse="true">
  <key column="ParentID"></key>
  <one-to-many class="Category"/>
</bag>
<set name="Products" table="Categories_Products">
  <key column="CategoryId"></key>
  <many-to-many column="ProductId" class="Product"></many-to-many>
</set>

當我嘗試創建數據庫時,出現以下錯誤:

失敗:INSERT語句與FOREIGN KEY SAME TABLE約束“ FK9AD976763BF05E2A”發生沖突。 數據庫“ CoderForTraders”的表“ dbo.Categories”的列“ CategoryId”中發生了沖突。 該語句已終止。

我在網上尋找了一些答案,但沒有找到答案。 謝謝你的幫助

這是缺少的部分:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="CBL.CoderForTraders.DomainModel" namespace="CBL.CoderForTraders.DomainModel" default-access="field.camelcase-underscore" default-lazy="true">

  <class name="Category" table="Categories" >
    <id name="_persistenceId" column="CategoryId" type="Guid" access="field" unsaved-value="00000000-0000-0000-0000-000000000000">
      <generator class="assigned" />
    </id>
    <version name="_persistenceVersion" column="RowVersion" access="field" type="int" unsaved-value="0" />

該錯誤發生在插入而不是表創建上。 您沒有顯示ID的映射,但是如果它是SQL Server中的標識列,則由於父記錄(類別屬性)不存在,因此無法插入第一條記錄。 一種解決方案可能是暫時刪除約束,插入引用自身的“根”記錄,然后重新添加約束。

我認為問題在於您必須提供一個明確的fk-constraint-name以避免命名colision:

<bag name="SubCategories">
  <key column="ParentID" foreign-key="fk_Category_ParentCategory"/>
  <one-to-many class="Category"/>
</bag>

在這里,您可以找到有關如何在NHibernate中映射樹的很好的教程。 由於它也使用模式生成,因此應該可以解決您的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM