将业务逻辑和服务调用推出控制器。需要反馈

时间:2019-05-29 02:15:56

标签: c# oop model-view-controller controller n-tier-architecture

我有一个MVC应用程序,我试图将业务逻辑推出控制器并推入模型(然后将这些模型映射到视图模型)。为此,我将服务和存储库注入模型中,然后将模型注入控制器中。

从那时起,我使用模型填充自身或返回自身列表,将其映射到控制器将要返回的视图模型。

问题:这个设计不好吗?专门使用此模型(如服务)来返回其自身的列表(即GetAllCars()返回List )或它的任何其他方面?

我应该尝试在模型中存储业务逻辑/数据访问吗?

我应该使用另一种方法来处理这种情况吗?

    public class CarsController : Controller
    {
        private readonly CarModel _carModel;

        public CarsController(CarModel carModel)
        {
            _carModel = carModel;
        }

        public ActionResult GetCars()
        {
            List<CarViewModel> carViewModels = new List<CarViewModel>();
            carViewModels = _carModel.GetAllCars(); //some type of mapping would happen here
            return View(carViewModels);
        }

        public ActionResult GetCar(int id)
        {
            CarViewModel carViewModel = new CarViewModel();
            carViewModel = _carModel.GetCarById(id);//mapping to carViewModel here.
            return View(carViewModel);
        }
    }

    public class CarModel
    {
        private readonly IDataRepo _dataRepo;

        public int Make { get; set; }
        public int Model { get; set; }
        public int Color { get; set; }

        public CarModel(IDataRepo dataRepo)
        {
            _dataRepo = dataRepo;
        }

        public CarModel()
        {

        }

        public List<CarModel> GetAllCars()
        {
            List<CarModel> carModels = new List<CarModel>();
            carModels = _dataRepo.Car.ToList(); //some type of mapping would happen here
            return carModels;
        }

        public void GetCarById(int id)
        {
            this = _dataRepo.GetById(id); //some type of mapping would happen here
        }
    }

    public class CarViewModel
    {
        public int Make { get; set; }
        public int Model { get; set; }
        public int Color { get; set; }
    }
'''

0 个答案:

没有答案