我有一个遗留的 asp.net Web 应用程序,它有 2 层,UI 和 BusinessLayer。UI项目是ASP.NET网站类型,BL是类库类型。BL 项目为我的应用程序的实体提供类,如客户、用户、员工等。每个类都有从数据库读取和从 DataReader 填充对象属性的方法。这意味着客户类包含我的客户对象和数据访问方法.
现在我也更改了 Web 应用程序以支持 MVC。旧网站(webforms)像以前一样工作,我正在制作的网站的新升级(添加管理功能来管理网站)在 ASP.NET MVC3 中。路由和一切正常。但我担心项目的结构/可维护性。
对于新的 MVC 部分,我必须为 CustomerViewModel、EmployeeViewModel 等少数实体创建 ViewModel。我创建了另一个名为“ CustomerService
”的类,使用类似的方法GetCustomerViewModel
,在该方法内部,我GetCustomerMethod
从现有的 BusinessLayer 调用并从对象(现有 BL 项目中提到的实体类型)读取属性值并将其分配给CustomerViewModel
(我将研究一些AutoMapper 稍后会为这个对象采样并从这个方法中返回它。我的视图将使用此对象在 UI 中显示数据。我创建“ CustomerService
”类的原因是,在将值设置为 CustomerViewModel 对象之前,我可能需要进行一些条件检查或一些业务验证。我认为这是一个“中间层/服务层”,这样我的控制器就会很薄。
从我的客户控制器
public ActionResult Details(int id)
{
MyProject.MVCViewModel.CustomerViewModel objCustomerVM;
objCustomerVM=MyProject.MVCMiddleLayer.CustomerService.GetCustomerViewModel(id);
return View(objCustomerVM);
}
在我的 CustomerViewModel
public static CustomerViewModel GetCustomerViewModel(int customerId)
{
//Create an object of new ViewModel
CustomerViewModel objCustomerViewModel = new CustomerViewModel ();
//Get an object from Existing BL of Customer of type ExistingBL.Customer
ExistingBL.Customer objCustOld=new Customer(customerId);
//Check some properties of the customer object and set values to the new ViewModel object
if(objCustOld.Type=="normal")
{
objCustomerViewModel.Priority=2;
}
else if(objCustOld.Type=="abnormal")
{
objCustomerViewModel.Priority=1;
objCustomerViewModel.Message ="We love you";
}
//Some other checking like this....
return objCustomerViewModel;
}
这是一个错误的方法吗?我的代码会乱吗?我对 ViewModel 不满意,因为它(几乎)是我现有 BL 实体的重复代码。解决这种情况的最佳方法是什么。我不确定在这种情况下是否使用存储库模式(我在大多数示例中都看到了)?我应该这样做吗?它将如何改进我的代码?