NHibernate的插入、删除、修改操作都很简单,下面列出的例子可以很容易的理解,但是其中的数据请根据实际情况来做相应的修改。
一、新增数据
DAL中新增代码如下:
public int CreateCustomer(Customer customer)
{
int newId = (int)session.Save(customer);
session.Flush();
return newId;
}
DAL.Test新增代码如下:
[Test]
public void CreateCustomerTest()
{
Customer customer = new Customer() { Firstname = "haha", Lastname = "newtest" };
int newId = _crudAcc.CreateCustomer(customer);
customer = _customerAcc.GetCustomerById(newId);
Assert.AreEqual(newId, customer.CustomerId);
}
二、删除数据
DAL中新增代码如下:
public void DeleteCustomer(Customer customer)
{
session.Delete(customer);
session.Flush();
}
DAL.Test新增代码如下:
[Test]
public void DeleteCustomerTest()
{
Customer customer = _customerAcc.GetCustomerById(2);
_crudAcc.DeleteCustomer(customer);
customer = _customerAcc.GetCustomerById(2);
Assert.IsNull(customer);
}
三、修改数据
DAL新增代码如下:
public void UpdateCustomer(Customer customer)
{
session.Update(customer);
session.Flush();
}
DAL.Test新增代码如下:
[Test]
public void UpdateCustomerTest()
{
Customer customer = _customerAcc.GetCustomerById(1);
customer.Firstname = "not luo again";
_crudAcc.UpdateCustomer(customer);
customer = _customerAcc.GetCustomerById(1);
Assert.AreEqual("1", customer.Firstname);
}
四、新增或修改数据
DAL新增代码如下:
public void SaveOrUpdate(IList<Customer> customers)
{
foreach (var c in customers)
{
session.SaveOrUpdate(c);
}
session.Flush();
}
DAL.Test新增代码如下:
[Test]
public void SaveOrUpdateTest()
{
IList<Customer> customers = _customerAcc.Where("last name changed");
foreach(var x in customers)
{
x.Lastname = "saveOrUpdateTest()";
}
Customer customer = new Customer() { Firstname = "saveOrUpdateTestName", Lastname ="saveOrUpdateTestName" };
customers.Add(customer);
_crudAcc.SaveOrUpdate(customers);
}
SaveOrUpdate()函数的意思是,如果数据存在则修改该数据,如果数据不存在则新增该数据