The contents of this section
Operational Data Overview
1. New Object
2. Delete objects
3. Update objects
4. Save updated objects
Conclusion
Operational Data Overview
We often refer to a unit of work that usually performs 1 or more operations, which are either committed or discarded/rolled back. Think about using LINQ to SQL, everything is in memory, and only the Datacontext.submitchanges () method is invoked to submit the changed data to the database, and LINQ to SQL commits or rolls back.
We use nhibernate, too, and you don't have to commit (or roll back) to the database if you only query the data and do not change its value.
Note: This section, based on the previous section of the source code, creates a new CRUD.cs class in the data access layer to write an action method that creates a new CRUDFixture.cs class for testing at the test layer of the data access.
1. New Object
Simple description: Create a new object; call Isession.save (); Sync ISession.
Example: Write the CreateCustomer () method at the data access layer to save the passed customer object in the database.
public int CreateCustomer(Customer customer)
{
int newid = (int)_session.Save(customer);
_session.Flush();
return newid;
}
We test this method, create a new customer object, call the CreateCustomer () method to return the newly inserted CustomerID, and again query the database for this object based on CustomerID.
[Test]
public void CreateCustomerTest()
{
var customer = new Customer() { Firstname = "YJing", Lastname = "Lee" };
int newIdentity = _crud.CreateCustomer(customer);
var testCustomer = _crud.GetCustomerById(newIdentity);
Assert.IsNotNull(testCustomer);
}
2. Delete objects
Simple description: Gets an object, invokes Isession.delete (), synchronizes ISession.
Description: Use Isession.delete () to remove the state of an object from the database. Of course, your application may still hold a reference to it. So, it's best to understand that the purpose of Delete () is to turn a persistent instance into a temporary instance. You can also delete many objects at once by passing a nhibernate query string to delete (). The order of Delete objects is not required and does not cause a FOREIGN key constraint violation. Of course, it is possible to raise a NOT NULL constraint conflict defined by a foreign key field.
Example: Write the DeleteCustomer () method at the data access layer to delete the customer object from the database.
public void DeleteCustomer(Customer customer)
{
_session.Delete(customer);
_session.Flush();
}
We tested this method by querying the database for a customer object with a CustomerID of 2, calling DeleteCustomer () method deletion, and again querying the database for the existence of this object based on CustomerID.
[Test]
public void DeleteCustomerTest()
{
var coutomer = _crud.GetCustomerById(2);
_crud.DeleteCustomer(coutomer);
var testCustomer = _crud.GetCustomerById(2);
Assert.IsNull(testCustomer);
}