NHibernate Unit Test
A simple unit test using Category and Product from Northwind - check the test result to see the SQL used (in particular, only one "INSERT" in the first unit of work).
Hidden here is the NHibernate configuration and session factory (because the UnitOfWork calls SessionManager which is a lazily loaded singleton). More commonly, there's a test setup/Initialize (or Application_Start) which initializes this.
[TestMethod]
public void TestWithUnitOfWork()
{
int newProductId;
using (var uow = new UnitOfWork())
{
//let's read
var categoryManager = new CategoryRepository(uow.Current);
var productManager = new ProductRepository(uow.Current);
var category = categoryManager.LoadProxy(2);
//No SQL (unless we did a Session.Get)
//add a product
var p = new Product
{
Category = category, //the proxy, just with Id
ProductName = "Eggs",
UnitPrice = 3,
QuantityPerUnit = "6"
};
//No SQL to get category
productManager.SaveOrUpdate(p); //save product
//No SQL even after "Save"
uow.Commit();
//SQL= INSERT INTO [Products] ... on commit
newProductId = p.Id;
}
//second unit of work (=new session and transaction), just to clean up
using (var uow = new UnitOfWork())
{
var productManager = new ProductRepository(uow.Current);
Product p = productManager.GetById(newProductId);
//SQL= SELECT * FROM [Products] WHERE ...
productManager.Delete(p);
//SQL= DELETE FROM [Products] WHERE ...
uow.Commit();
}
}