我有2个db表和类结构使用nhibernate,如下所示。
DB
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; }
}
映射文件
customer.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>
address.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位客户保存到customers表,将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)
以上代码仅将数据插入到customers表中。如何将此数据插入客户和地址表?
答案 0 :(得分:1)
我们需要设置casacde
设置。只需以这种方式更改多对一映射:
<many-to-one name="BillingAddress" class="Address" cascade="all" />
<many-to-one name="ShippingAddress" class="Address" cascade="all" />
这将允许NHibernate持久保存新的Address
并更新现有的,同时仅调用Customer
实例进行保存/更新。