ASP .NET MVC 3 Models + stored procedures

前端 未结 4 1425
无人及你
无人及你 2021-02-10 12:35

Im, new in ASP MVC and I don\'t know how to create Models which base on stored procedures from my db. I have already database which works with another application, and my web pa

4条回答
  •  天涯浪人
    2021-02-10 13:06

    You could start with some abstraction indicating your intent:

    public interface IMyRepository
    {
        SomeModel Get(int id);
    }
    

    then you could write an implementation which will use your stored procedure:

    public class MyRepositorySql: IMyRepository
    {
        public SomeModel Get(int id)
        {
            ... call your stored procedure
        }
    }
    

    then design your controller so that it takes this abstraction as argument:

    public class MyController: Controller
    {
        private readonly IMyRepository _repository;
        public MyController(IMyRepository repository)
        {
            _repository = repository;
        }
    
        public ActionResult Index(int id)
        {
            var model = _repository.Get(id);
            return View(model);
        }
    }
    

    Now all that's left is to configure your DI framework to pass the proper implementation into the controller's constructor. As you can see now the controller is completely decoupled from the way data is fetched. It doesn't really matter whether you are using StoredProcs, some ORM or whatever in your data access layer.

提交回复
热议问题