How do I use DTO's with EF, Autofac, and a generic data repository?
I'm in the process of setting up a new project and have configured my DI/IoC (Autofac), using a generic repository for data access through EF, and created an OData service endpoint, ContentTypesController
.
Here's the top part of the controller:
public class ContentTypesController : ODataController, IContentTypesController
{
// add repository reference
private readonly IRepository<ContentType> _repository;
private ProjectV001Context _db = new ProjectV001Context();
/// <summary>
/// Constructor - setup for DI
/// </summary>
/// <param name="contentTypeRepository"></param>
public ContentTypesController(IRepository<ContentType> repository)
{
_repository = repository;
}
// GET odata/ContentTypes
[Queryable]
public Task<IQueryable<ContentType>> Get(ODataQueryOptions<ContentType> options)
{
// mock
var userId = 102;
//var unitOfWork = new Repository.UnitOfWork(_db); <-- removed from the original question
var result = _repository.Query()
.Filter(u => u.UserId == userId)
.GetAsync();
return result;
}
ContentType
is the EF class in Project.DAL.Data.Models, which contains fields that do not need to be seen/used by the client - ie. UserId. In inserting or updating methods, the value of this field will be set pragmatically.
My DTO is located in Project.Core.ContentTypes.
1) Am I using the unit of work pattern here correctly?
2) I want my methods to return the DTO, and not all the fields from the actual entity object. How do I set this up?
-- UPDATE --
In a previous project (and different repository) I was implementing the UoW as follows:
public class ContentTypesController : ODataController { private ProjectDbContext _db = new ProjectDbContext();
public IEnumerable<ContentType> Get(ODataQueryOptions<ContentType> options)
{
var unitOfWork = new Project.Repository.UnitOfWork(_db);
var contentTypes = options.ApplyTo(unitOfWork.Repository<ContentType>().Queryable
.OrderBy(c => c.Description))
.Cast<ContentType>().ToList();
unitOfWork.Save(); // includes Dispose()
return contentTypes;
}