Am I right that using NHibernate (or any other ORM) removes the necessity of DAL? Or not?
I was trying to think of how to answer this question but the answer is NO, it doesn't remove the neccesity of a DAL rather than becomes part of that DAL, what you were doing before no doubt was having access objects which called either sql code build in code or was calling stored procs.
It was then constructing say a Bill business object with data perhaps from multiple tables and then returning that. It was a lot of hard work and usually involved maintainance by itself.
NHibernate takes the heavy lifting work out of this task (and does other things) but you still may want "Manager" classes as part of the data access layer to do manipulation before objects are returned etc.
So allthough I'm doing a terrible job of explaining it, NHibernate doesn't remove the need for a DAL it just changes what your DAL is made up of.
You need a DAL, the question is what do you do in the DAL. In a .NET project with NHibernate, I use this organisation
- MyProject.Core.DomainModel : in this project only the .cs and mapping files (.hbm.xml)
- MyProject.Repo : in this classes you use NHibernate method like Get, Load, make query ....
- MyProject.Service : from these classes, I call the MyProject.Repo methods
- MuProject.UI : ASP.NET, ASP.NET MVC, Winforms .....
- MyProject.Service.Tests : all the unit test to test the service
I give you an example, I'd like get all active Employee and sort them.
in my UI, I call MyProject.Service.EmployeeService.GetActive(); in getGetActive, I call a function in PyProject.Repo to get active employee. When I have the result back (in the service method), I do an order with Linq and return the list ordered.
To resume, the Repo project, it's access DB via NHibernate and Service it's the business.
It's my opinion, it's like this I do it's may be not the best way, not the only way, but it's my way :)
The NHibernate ISession can be used as a Unit of Work and a simple IRepository. In this sense it can replace some of the mundane DAL stuff.
For example:
using(var uow = new UnitOfWork())
{
var customerRepository = new Repository<Customer>(uow);
var customer = customerRepository.Get(id);
customer.DoSomething();
uow.commit();
}
could be:
using(var session = sessionFactory.OpenSession())
{
using(var tx = session.BeginTransaction())
{
var customer = session.Load<Customer>(id);
customer.DoSomething();
tx.commit();
}
}
Obviously you still want to control who 'knows' what an ISession is, so there is a reason to keep the idea of DAL in your code. But you have removed UoW and Repository code and just let NHibernate do it for you. It does blur things some.
Most people still use an IRepository even with NHibernate. It is an opinionated topic.
The subjectiveness continues on the way to queries. Some people prefer having specialized query methods on the repository. Others prefer to have the queries as their own object (Query Object). There is no right or wrong answer.