1

我有 2 个与 nhibernate 一起使用的数据库表和类结构,如下所示。

D B

在此处输入图像描述

C# poco 类如下。

客户类

public class Customer
{
    public virtual int CustomerID { get; set; }
    public virtual string CustomerName { get; set; }
    public virtual string Title { get; set; }
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
    public virtual string Mobile { get; set; }
    public virtual string Phone { get; set; }
    public virtual string Email { get; set; }

    public virtual Address BillingAddress { get; set; }
    public virtual Address ShippingAddress { get; set; }
}

地址类

public class Address
{
    public virtual int AddressID { get; set; }
    public virtual string AddressLine { get; set; }
    public virtual string City { get; set; }
    public virtual string State { get; set; }
    public virtual int ZIP { get; set; }
    public virtual string Fax { get; set; }
    public virtual string Country { get; set; }
}

映射文件

客户.hbm.xml

  <class name="Customer" table="Customers">
    <id name="CustomerID">
      <generator class="native" />
    </id>
    <property name="CustomerName" length="100" />
    <property name="Title" length="10" />
    <property name="FirstName" length="60" />
    <property name="LastName" length="60" />
    <property name="Mobile" length="15" />
    <property name="Phone" length="15" />
    <property name="Email" length="100" />
    <many-to-one name="BillingAddress" class="Address" />
    <many-to-one name="ShippingAddress" class="Address" />
  </class>

地址.hbm.xml

  <class name="Address" table="Addresses">
    <id name="AddressID">
      <generator class="native" />
    </id>
    <property name="AddressLine" length="255" />
    <property name="City" length="30" />
    <property name="State" length="30" />
    <property name="ZIP" />
    <property name="Fax" length="15" />
    <property name="country" length="50" />
  </class>

我正在使用 nhibernate 会话创建数据库表。表创建良好。使用上述结构,如果我想保存指定了 2 个地址类型的客户,如何将 1 个客户保存到客户表和 2 个地址到地址表?请参阅以下示例代码。

Address b_address = new Address();
Address s_address = new Address();
Customer customer = new Customer();

b_address.addressLine = "No.23, New Road";
b_address.City = "Newyork";
// more data

s_address.addressLine = "No.54, Old Road";
// more data

customer.CustomerName = "David";
// more customer data
customer.BillingAddress = b_address;
customer.ShippingAddress = s_address;

//saving the session.
session.save(customer)

上面的代码只将数据插入到客户表中。我如何将这个插入数据同时插入到客户和地址表中?

4

1 回答 1

1

我们需要casacde发挥设置。只需以这种方式更改多对一映射:

<many-to-one name="BillingAddress" class="Address" cascade="all"  />
<many-to-one name="ShippingAddress" class="Address" cascade="all"  />

这将允许 NHibernate 持久化新的Addresses 并更新现有的,同时只调用Customer要保存/更新的实例。

于 2012-11-24T06:10:03.483 回答