The preceding method creates a session Factory
Let's first create a new category object. We can do this by using the following code snippet:
VaR Category =NewCategory
{
Name ="Beverages",
Description ="Some description"
};
Next, we want to save this new category object and we can do so by using the following code:
VaR id = session. Save (category );
The value that is returned from the Save method corresponds to the ID of the newly createdcategory object.
Now, let's create a product. the product has a reference to a category object. before we can save a product, the corresponding category object must have been persisted to the database. the following code wocould work:
VaR Category =NewCATEGORY {name ="Beverages"};
VaR Product =NewProduct {name ="Milk", Category = Category };
Session. Save (category );
Session. Save (product );
The Session object can also be used to delete an existing object from the database. The command to do so is as simple as the following code:
Session. Delete (category );
Here, the category object we pass as a parameter to the delete method corresponds to the one we want to remove from the database.
Reading from the database
Persisting data into a database is surely important, but we also want to be able to reuse this data and thus must have a means to access it. the nhib1_session object provides us with this possibility. we can use the session object directly to access a single object in the database, which is identified by its primary key by using the following code:
VaR Category = session. Get <Category> (1 );
Nhibernate will query the database for a category record in the category table having an ID of 1. nhibernate will then take this data and create a category object from it. we also say, "nhib1_rehydrates an object ".
If we want to read not only a single object, but a list of objects from the database, we can use the LINQ to nhib1_provider to do so. the following statement will read all records from the category table and generate a list of the category objects out of it:
VaR categories = session. query <Category> ();
We can even go a step further and, for example, query a list Of all discontinued products sorted by their name with the following statement:
VaR products = session. query <product> ()
. Where (P => P. discontinued)
. Orderby (P => P. Name );