我正在使用ASP.NET MVC 2和实体框架构建我的第一个Web应用程序。我正在使用存储库模式。从Stack Overflow和其他网站收集的信息看来,共识是每个域模型对象有一个控制器,每个聚合根对象有一个存储库。ASP.NET MVC /实体框架:通过聚合根存储库访问聚合对象
我的问题是我应该如何通过聚合根存储库访问非根集合对象。在我处理的例子中,有一个Customer模型和一个Boat模型。船只只能以客户的FK参考存在,而船只只需在客户环境中参考。这导致我相信我有这两个对象的聚合,并且客户是根。
现在在我的船控制器我有一个编辑操作方法:
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
}
}
我的问题是我怎么想检索信息库中的船对象?
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访问船似乎更合理,但是我无法弄清楚如何返回一个单独的船对象,而不必在LINQ查询中重复我自己,因为它并不适合我。
我知道我还有很多东西需要学习,所以希望你能指点我正确的方向!
谢谢!
感谢您的详细回复。因为我是新手,所以我想确保我没有违反一些基本规则或任何东西。 – 2010-08-07 16:44:33