我正在使用 ASP.NET MVC 2 和实体框架构建我的第一个 Web 应用程序。我正在使用存储库模式。从我在 Stack Overflow 和其他网站上收集的信息来看,似乎共识是每个域模型对象有一个控制器,每个聚合根对象有一个存储库。
我的问题是我应该如何通过聚合根存储库访问非根聚合对象。在我正在处理的示例中,有一个 Customer 模型和一个 Boat 模型。船只能与客户的 FK 引用一起存在,并且船只需要在客户的上下文中被引用。这使我相信我有这两个对象的聚合,并且客户是根。
现在在我的 Boats 控制器中,我有一个 Edit 操作方法:
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
}
}
我的问题是如何在存储库中检索 Boat 对象?
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);
}
}
我可以从客户存储库中引用 db.Boats 吗?它似乎是最干净的,但这意味着我将不得不更改我的 FakeCustomersRepository 以获得客户和船只列表。
通过 db.Customers 访问 Boat 对我来说似乎更合理,但是我无法弄清楚如何返回单个 Boat 对象而不在 LINQ 查询中重复自己,这真的不适合我。
我知道我还有很多东西要学,所以希望你能指出我正确的方向!
谢谢!