NHibernate Mapping问题

时间:2010-04-14 21:51:21

标签: c# nhibernate mapping

我的数据库由我的NHibernate映射文件驱动。

我有一个类似于以下内容的类:

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" />

2 个答案:

答案 0 :(得分:1)

错误发生在插入,而不是表创建。您没有显示ID的映射,但如果它是SQL Server中的标识列,则无法插入第一条记录,因为父记录(类别属性)不存在。一种解决方案可能是暂时删除约束,插入引用自身的“根”记录,然后再添加约束。

答案 1 :(得分:0)

我认为问题是你必须提供一个明确的fk-constraint-name来避免命名colision:

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

Here你可以找到一个关于如何在NHibernate中映射树的好教程。由于它也使用模式生成,它应该可以解决您的问题。