How to access the database from the api controller?

我是研究僧i 提交于 2019-12-13 17:05:30

问题


I am doing a mobile app with Angular and MVC. I am doing my app calling some dummy data from the json model in the web api. Check my code below:

 private IEnumerable<JsonModel> events = new JsonModel[]
    {
       new JsonModel {Id = 1, Title = "title1"}
       new JsonModel {Id = 2, Title = "title2"}
      };


        // GET api/<controller>
        public IEnumerable<JsonModel> Get()
        {
            return events;
        }

        // GET api/<controller>/5
        public JsonModel Get(int id)
        {
            return events.FirstOrDefault(e => e.Id == id );
        }

What I want to do now is to connect my project to the real database. How can I do that?


回答1:


As the ZenCoder mentioned, there are lots of ways to access your database, one of them is the repository pattern, here's some info about it:

https://msdn.microsoft.com/en-us/library/ff649690.aspx

This is one of the most famous patterns used nowadays and when working with the asp.net mvc framework is used with the Entity Framework. Here's a nice tutorial which explains how to use it with the ASP.NET Web Api2:

http://www.asp.net/web-api/overview/data/using-web-api-with-entity-framework/part-1

any question just let me know.




回答2:


Configuring access to the database file itself can be also the source of your isssue, look here: Configuring Permissions for an Access Database

Hope it helps



来源:https://stackoverflow.com/questions/28412420/how-to-access-the-database-from-the-api-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!