我在 C# 和 Razor 中有一个 ASP.NET MVC3。应用程序的架构分为数据访问层(EF 类 + 存储库)、服务层、控制器、ViewModels 和 View。
我有两个 EF 类Products
(key ProdId
)和ProductCategories
(key ProductCategoryId
)。
他们通过一对多的关系在ProdCatId
类Products
中作为外键和ProductCategoryId
在类中关联ProductCategories
。
当然还有一个从类到的导航属性 。hasCategory
Products
ProductCategories
我的存储库类中有该方法:
public IQueryable<Products> GetAllProducts()
{
return productDB.Products;
}
现在我想在我的视图中显示所有带有ProductCategoryName
(不是ProdCatId
)对应类别的产品。要在我使用的存储库中访问此信息(productDB 是 EF 类):
productDB.Products.Where(n => n.ProdId == prodId)
.Select(m => m.hasCategory.ProductCategoryName).First();
为了在我的视图上获得这些信息,我应该使用我的服务层中的这段代码,或者更糟糕的是我的ViewModel中的代码。但是,通过这种方式,我会在想要保持分离的组件(服务层和 EF 或 ViewModel 和 EF)之间创建耦合。
如果我将这个值从我的存储库(方法string GetProductCategory(int ProdId)
)获取到我的服务层,连同GetAllProducts().ToList()
,我将有两个对象:
1) 一个List<Products>
2) 一个string
如何将这些值传递给我的控制器,然后包装在 ViewModel 中?我应该ProductInfo
在包装这些数据的服务层中创建一个类吗?此解决方案创建了Controller、ViewModel和类ProductInfo之间的耦合。
不创建耦合的正确做法是什么?