NHibernate 多对一映射

NHibernate many-to-one mapping

实体类:

public class Purchase
{
   public virtual int PurchaseId { get; set; }
   public virtual int CustomerId { get; set; }
   public virtual Customer Customer { get; set;}
}

public class Customer
{
    public virtual int CustomerId { get; set; }
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
}

休眠配置:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="xxx" assembly="xxx">
  <class name="Purchase" table="Purchase">
    <id name="PurchaseId" column="PurchaseId" />
    <many-to-one name="Customer" column="CustomerId"/>
  </class>
</hibernate-mapping>

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="xxx" assembly="xxx">
  <class name="Customer" table="Customer">
    <id name="CustomerId" column="CustomerId" />
    <property name="FirstName" column="FirstName" />
    <property name="LastName" column="LastName" />
  </class>
</hibernate-mapping>

我正在尝试将新购买的商品保存到数据库中:

 using (var session = _sessionFactory.Create())
 {
     var customer = new Customer { CustomerId = 1, FirstName = "John", LastName = "Smith" };
     var purchase = new Purchase { PurchaseId = 1, Customer = customer };

     session.Save(purchase);
     session.Flush();
 }

采购 table 对客户有 FK table。

我得到:"SqlException: Cannot insert the value NULL into column 'CustomerId', table 'ORM.dbo.Purchase'; column does not allow nulls. INSERT fails."

我想知道,我做错了什么。 非常感谢您的回答。

问题可能在于 NHibernate 并不知道 CustomerId 的什么值要插入到 Purchase table 中,因为它不知道如何获取该键。

能否请您尝试更改映射以包含 generator

请注意,根据 NHibernate Docs

generator: The name of a generator class to use for generating unique identifiers for instances of the persistent class. See the generator element. Specifying either the attribute or the element is required. The attribute takes precedence over the element.

现在,具体选择哪个生成器是一个更大的话题,取决于您的用例,请参阅

中的一些信息

如果您想在代码中分配键,您应该选择 assigned 生成器,见下文

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="xxx" assembly="xxx">
  <class name="Purchase" table="Purchase">
    <id name="PurchaseId" column="PurchaseId" generator="assigned" />
    <many-to-one name="Customer" column="CustomerId"/>
  </class>
</hibernate-mapping>

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="xxx" assembly="xxx">
  <class name="Customer" table="Customer">
    <id name="CustomerId" column="CustomerId" generator="assigned"/>
    <property name="FirstName" column="FirstName" />
    <property name="LastName" column="LastName" />
  </class>
</hibernate-mapping>