如何从api控制器访问数据库? [英] How to access the database from the api controller?

查看:120
本文介绍了如何从api控制器访问数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Angular和MVC做一个移动应用程序.我正在做我的应用程序,它从Web API中的json模型中调用了一些虚拟数据.检查下面的代码:

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?

推荐答案

正如ZenCoder所述,有很多方法可以访问数据库,其中之一是存储库模式,以下是有关它的一些信息:

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

这是当今最著名的模式之一,当与asp.net mvc框架一起使用时,它与Entity Framework一起使用.这是一个很好的教程,解释了如何将其与ASP.NET Web Api2一起使用:

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

任何问题都让我知道.

这篇关于如何从api控制器访问数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆