My NHibernate Trip (ii): additions and deletions

Source: Internet
Author: User
Tags assert

on a blog, through a small demo to roughly introduce the use of nhibernate process. Using NHibernate, the most fundamental is "CRUD" (Increase and deletion). What we often call a unit of work, typically performing 1 or more operations, is either committed or discarded/rolled back for these operations. If you only query the data and do not change its value, you do not need to commit (or roll back) to the database. For query operations, the content is more, this time is not involved. This article only introduces the deletion and modification operation.

Note: This section, based on the previous section of the source code, in the data access layer of the new SessionCRUD.cs class used to write the operation method, in the test layer to create a new CRUDFixture.cs class for testing.



New Object
Synchronize to the database by calling the Isession.save () method.
Example: Write the CreateCustomer () method in the number CRUD.cs class to save the passed-in customer object in the database.
<summary>///new Object///</summary>///<param name= "Customer" ></param>///<returns> </returns>public int CreateCustomer (Customer customer) {    int newid = (int) _session. Save (customer);    _session. Flush ();    return newid;}
Test this method . creates a new customer object, calls the CreateCustomer () method to return the newly inserted CustomerID, and again queries the database for the existence of the object based on CustomerID.
<summary>///Create test//</summary>[test]public void Createcustomertest () {    var customer = new Customer ( {Firstname = "Lianhai", Lastname = "Zhang"};    int newidentity = _crud. CreateCustomer (customer);    var testcustomer = _crud. Getcustomerbyid (newidentity);    Assert.isnotnull (Testcustomer);}
Take a
look at the test :

results in the database :




Delete Object
Locate an object, call Isession.delete (), and synchronize to the database.
But there is a problem with this approach, which is to first isolate the record (SELECT), then map it to an entity, and then pass the entity back to perform the delete operation. This processing may be able to solve a series of problems such as caching and database synchronization.
HQL is a unique operating language of NHibernate, it can understand, since it can be understood so that the relationship with the cache (not measured), but the tracking of SQL statements, or the first query after the deletion, the only difference is to return more than one affect the number of rows.
If you do not use the NHibernate cache feature, you can consider using the Createsqlquery method of deletion, which is ignored here, the following blog will be introduced.
Example: Writing the DeleteCustomer () method at the data access layer deletes the customer object from the database.
<summary>///Delete object///</summary>///<param name= "Customer" ></param>public void DeleteCustomer (Customer customer) {    _session. Delete (customer);    _session. Flush ();}
Test this method . Query the Customer object with CustomerID 1 in the database, call the DeleteCustomer () method to delete it, and then query the database for the existence of the object again according to CustomerID.
<summary>///Delete test//</summary>[test]public void Deletecustomertest () {    var coutomer = _crud. Getcustomerbyid (1);    _crud. DeleteCustomer (Coutomer);    var testcustomer = _crud. Getcustomerbyid (1);    Assert.isnull (Testcustomer);}
For some reason, the test result DELETE statement did not come out, but the database has changed. ( the following update and save the update also did not come out of the corresponding statement, the test of the picture is temporarily not posted ) directly look at the results in the database . The record is out of the way.



Updating Objects
Gets an object, alters some of its properties, invokes Isession.update (), and synchronizes ISession.
Example: Writing the UpdateCustomer () method at the data access layer modifies the Customer object.
<summary>///Update object///</summary>///<param name= "Customer" ></param>public void UpdateCustomer (Customer customer) {    _session. Update (customer);    _session. Flush ();}
Test this method. Query the Customer object with CustomerID 2 in the database and modify its FirstName property value, call the UpdateCustomer () method Update, The FirstName value of the Customer object that CustomerID to 1 in the database is queried again as the modified value.
<summary>///Update Test///</summary>[test]public void Updatecustomertest () {    var customer = _crud. Getcustomerbyid (2);    Customer. Firstname = "LH";    _crud. UpdateCustomer (customer);    var testcustomer = _crud. Getcustomerbyid (2);    Assert.AreEqual ("LH", customer.) Firstname);}

looking at the results in the database , "Lianhai" is changed to "LH":




Save Updated Object
will you come up with this question? What are the objects that you just created, and which are the modified ones? We need to save it to the database for the object we just created, and we need to update it to the database for the modified object. NHibernate can automatically determine whether an insert or update should be performed. This is the saveorupdate () method , and when we execute this method, NHibernate completes the following work:
    • Check if the object already exists in the session.
    • If the object is not present, call Save (object).
    • If the object exists, check to see if the object has changed.
    • If the object changes, call Update (object).
Take a look at the following example to illustrate this situation, write the Saveorupdatecustomer () method at the data access layer, save the Update Customer object list, loop through the Customer object in the list, and call Isession.saveorupdate ( Object) method to save the update for each customer object.
<summary>///Save Update object///</summary>///<param name= "Customer" ></param>public void Saveorupdatecustomer (ilist<customer> customer) {    foreach (var c in Customer)    {        _session. Saveorupdate (c);    }    _session. Flush ();}

Test this method. first in the database query FirstName is the Customer object LH and modify its LastName property value, this object is existing in the database, and changed, and then create a new 2 customer object, the two objects in the database does not exist, is newly created. Call the Saveorupdatecustomer () method to save the updated object, which is to update the previously modified object and save the newly created 2 objects later.

<summary>///Save Update test//</summary>[test]public void Saveorupdatecustomertest () {    ilist< Customer> customers=new list<customer> ();    var oldcustomer = _crud. Getcustomerbyid (2);    Oldcustomer.lastname = "Zhang";    Customers. ADD (Oldcustomer);    var C1 = new Customer () {Firstname = "Lianhai", Lastname = "Zhang"};    var C2 = new Customer () {Firstname = "Lianhai", Lastname = "Zhang"};    Customers. ADD (C1);    Customers. ADD (C2);    _crud. Saveorupdatecustomer (customers);}
look at the database, the first data is updated, the following is the new addition:



Summarize

The above is simple to delete the object and modify the operation. Of course, this section manipulates object operations, involving the state of the object in NHibernate, where there are three states for a particular isession: instantaneous (transient) objects, persisted (persistent) objects, free (detached) objects. This section does not mention, later in the discussion session of the time to introduce.

My NHibernate Trip (ii): additions and deletions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.