I use Entity Framework Code First, but the following concept is the same (for non-trivial projects):
I always keep my DAL classes out of my actual business layers. That way it lessens the impact of DB changes on your application. I never use DAL classes anywhere other than my DAL project.
My current project makes use of DDD, any the layout is similar to the following (massively simplified):
MainApp
MainApp.Domain
|...IRepositories
|...AggregrateX
|...AggregrateY
MainApp.Dal
|...Models
|...Repositories
- MainApp - Can see Domain, but not DAL
- MainApp.Dal - Can see Domain, but not
MainApp
The DAL repository methods make use of AutoMapper:
public Customer Get(int customerId)
{
using (var context = GetContext())
{
var entity = context.Customers.Where(x=>
x.CustomerId == customerId).Single();
return Mapper.Map<DtoCustomer, Customer>(entity);
}
}
public void Save(Customer customer)
{
using (var context = GetContext())
{
var entity = context.Customers.Where(x=>
x.CustomerId == customer.CustomerId).Single();
Mapper.Map(customer, entity);
context.SaveChanges();
}
}
Thereby allowing total separation between my business classes and my actual DAL/DTO objects. It, in theory, allows the entire backend to be changed without affecting any of the business logic. What I've not shown is that I then also ensure Domain/Business objects are never seen by the presentation layer as I map to and from Input/View Models instead via a facade.
Basically, what I'm left with is a domain layer that contains all business logic that doesn't care what's using it or how it's populated or how it's persisted, and a DAL layer who's sole purpose is the population and persistence of my domain/business classes.
However, this only really makes sense for large projects. I would just use the DAL classes on trivial/small projects.