1
我有2个db表和使用nhibernate工作的类结构,如下所示。将数据保存到多个表中
DB
C#POCO类是如下。
Customer类
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个客户保存到客户表以及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表中。我如何将这个插入数据传递给客户和地址表?
太棒了。顺便说一下,我们可以使用级联的其他选项是什么? – BlueBird
以下是文档http://nhforge.org/doc/nh/en/index.html#mapping-declaration-manytoone。摘录:'cascade =“all | none | save-update | delete”'。 **所有**可能更适合您的情况,因为当客户被删除时,他的所有地址都应该如此。 –
我在另一个表中有另一种情况,所有的save-update或delete都不起作用。表1中有充足的数据。表2与它有多对一的关系。我只想保留Table1的主键,但不应该向Table1中添加新的数据。我可以使用哪一个? (考虑地址 - > [多对一] - >国家)国家表已经与国家填写。地址表应该包含国家的主键。当加载数据时,应使用国家POCO加载完整的国家对象。 – BlueBird