My repositories deal with and provide persistence for a rich domain model. I do not want to expose the anemic, Entity Framework data entity to my business layers, so I need
I like using custom-built Extension methods to do the mapping between Entity and Domain objects.
A simple example:
public static class LevelTypeItemMapping
{
public static LevelTypeModel ToModel(this LevelTypeItem entity)
{
if (entity == null) return new LevelTypeModel();
return new LevelTypeModel
{
Id = entity.Id;
IsDataCaptureRequired = entity.IsDataCaptureRequired;
IsSetupRequired = entity.IsSetupRequired;
IsApprover = entity.IsApprover;
Name = entity.Name;
}
}
public static IEnumerable ToModel(this IEnumerable entities)
{
if (entities== null) return new List();
return (from e in entities
select e.ToModel());
}
}
...and you use them like this.....
using (IUnitOfWork uow = new NHUnitOfWork())
{
IReadOnlyRepository repository = new NHRepository(uow);
record = repository.Get(id);
return record.ToModel();
records = repository.GetAll(); // Return a collection from the DB
return records.ToModel(); // Convert a collection of entities to a collection of models
}
Not perfect, but very easy to follow and very easy to reuse.