2010-04-14 193 views
0

我的数据库是由我的NHibernate映射文件驱动的。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语句冲突与外键相同的表约束“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" /> 

回答

1

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

+0

这对我来说很有意义。我会马上尝试! – 2010-04-14 23:11:07

+0

你知道吗。那样做了。许多非常感谢杰米 – 2010-04-14 23:16:27

+0

完全有意义。看不到它。 – zoidbeck 2010-04-15 22:38:29

0

我认为问题是,你必须提供一个明确的FK-约束名称,以避免命名colision:

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

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

+0

不幸的是,我仍然得到相同的错误 – 2010-04-14 22:33:40

+0

你有没有尝试没有inverse =“true”?对不起,现在需要一些睡眠。 – zoidbeck 2010-04-14 22:47:17

+0

是同样的结果。 Thks for your help – 2010-04-14 22:56:55