I'm in the process of building my first web application using ASP.NET MVC 2 and the Entity Framework. I am using the repository pattern. From information I have gathered on Stack Overflow and other websites it appears that the consensus is to have one one controller per domain model object and one repository per aggregate root object.
The question I have is how I should be accessing non-root aggregate objects through the aggregate root repository. In the example I am dealing with there is a Customer model and a Boat model. Boats can only exist with a FK reference to a Customer and Boats only need to be referenced within the context of a Customer. This led me to believe that I had an aggregate with these two objects and that the Customer was the root.
Now in my Boats controller I have an Edit action method:
public class BoatsController : Controller
{
private ICustomersRepository customersRepository;
public BoatsController(ICustomersRepository customersRepository)
{
this.customersRepository = customersRepository;
}
public JsonResult Edit(int id, FormCollection collection)
{
var boat = customersRepository.GetBoat(id);
// Update boat
}
}
My question is how do I want to retrieve the Boat object in the repository?
public class SQLCustomersRepository : ICustomersRepository
{
DatabaseEntities db = new DatabaseEntities();
public Boat GetBoat(int id)
{
return db.Boats.SingleOrDefault(x => x.ID == id);
// OR
return db.Customers.Where(x => x.Boats.Any(y => y.ID == id)
.Select(x => x.Boats.FirstOrDefault(y => y.ID == id);
}
}
Is it acceptable for me to reference db.Boats from the Customers Repository? It seems to be the cleanest, but it would mean that I would have to alter my FakeCustomersRepository to have a List of Customers AND Boats.
It seemed more reasonable to me to access the Boat through db.Customers, however I couldn't figure out how to return a single Boat object without repeating myself in the LINQ query which really didn't sit well with me.
I know I still have a lot to learn so hopefully you can point me in the right direction!
Thanks!