XpressionMapper leverages AutoMapper to transform business model expressions into data model expressions. Expression mapping provides a couple of advantages.
- Improved separation of concerns: The Entity Framework (or other ORM) layer has no knowledge of the business model.
- Removes the need for projection in the data layer or the need to return an IQueryable object from the data layer.
The service layer references business model classes only and has no knowledge of the data model (POCOs) or the EF (Entity Framework) layer
public class PersonService : IPersonService { private IPersonRepository repository;
public ICollection<PersonModel> GetList(Expression<Func<PersonModel, bool>> filter = null, Expression<Func<IQueryable<PersonModel>, IQueryable<PersonModel>>> orderBy = null, ICollection<Expression<Func<PersonModel, object>>> includeProperties = null) { ICollection<PersonModel> list = repository.GetList(filter, orderBy, includeProperties); return list.ToList(); }
}
The repository layer references the business model and data model (POCOs) classes and has no knowledge of the EF layer. public class PersonRepository : IPersonRepository { private IPersonStore store;
public ICollection<PersonModel> GetList(Expression<Func<PersonModel, bool>> filter = null, Expression<Func<IQueryable<PersonModel>, IQueryable<PersonModel>>> orderBy = null, ICollection<Expression<Func<PersonModel, object>>> includeProperties = null)
{
Expression<Func<Person, bool>> f = filter.MapExpression<Func<PersonModel, bool>, Func<Person, bool>>();
Expression<Func<IQueryable<Person>, IQueryable<Person>>> mappedOrderBy = orderBy.MapExpression<Func<IQueryable<PersonModel>, IQueryable<PersonModel>>, Func<IQueryable<Person>, IQueryable<Person>>>();
ICollection<Expression<Func<Person, object>>> includes = includeProperties.MapExpressionList<Func<PersonModel, object>, Func<Person, object>>();
ICollection<Person> list = store.Get(f, mappedOrderBy == null ? null : mappedOrderBy.Compile(), includes);
return Mapper.Map<IEnumerable<Person>, IEnumerable<PersonModel>>(list).ToList();
}
}
The EF layer references the data model (POCOs) and has no knowledge of the business model.
public class PersonStore : IPersonStore
{
public IList<Person> Get(Expression<Func<Person, bool>> filter = null, Func<IQueryable<Person>, IQueryable<Person>> orderBy = null, ICollection<Expression<Func<Person, object>>> includeProperties = null)
{
IList<Person> list = null;
using (IPersonUnitOfWork unitOfWork = new PersonUnitOfWork())
{
list = new PersonDbMapper(unitOfWork).Get(filter, orderBy, includeProperties);
}
return list;
}
}