Try. NET core-to build Webapi with. NET core + Entity FrameWork core (i)

Source: Internet
Author: User

I want to try. NET core for a long time, and have not been there, go home today, put aside everything, first build a. NET core demo come out to play.

Cut the crap, I'm heading straight to the subject:

First, the development environment

VS2015 Update3

Microsoft. NET Core Tools (Preview 2)

Originally wanted to use vs code, but in the simplest principle, here first with VS 2015, I am not a masochist, why there is a good tool to put here, you say?

Second, the new solution

Unlike the ASP. Net-era, create a new solution directly on the left, select, and then Project template, choose ASP. Application (. NET core).

Then fill in the Solution name and project name and select Save Path (which is exactly the same as before). Then to the second step, choose the Web API template, authentication method choose No Authentication (here is just demo, authentication we don't toss it, after all, this is often very complex). and remove his default host in Cloud tick (if you have an azure server, you can hook it up).

Here, the project is created. You can directly point to the top of the run, the project to run, will directly open a default API (Valuecontrller).

Here I have created a. NET Core Class library project, which is used as the database access layer, named DataAccess, which is no different from the original. NET Era Class library project, but needs to build the. NET Core Class library.

The new completed solution structure is as follows:

Iii. beginning of coding

Here I take the first 10 records of the Address table in a local database as an example.

1. Create a new entity class address

make its field correspond to database one by one, remember to set the [key] attribute label on the primary key (ID).

 Public classAddress {[Key] PublicGuid Id {Get;Set; }  Public stringOpenId {Get;Set; } /// <summary>        ///Recipient's name/// </summary>         Public stringName {Get;Set; } /// <summary>        ///Detailed delivery address (currently limited to Yulin College)/// </summary>         Public stringdetailaddress {Get;Set; } /// <summary>        ///Contact Phone/// </summary>         Public stringTel {Get;Set; } /// <summary>        ///whether the default address/// </summary>         Public BOOLIsDefault {Get;Set; } }
2. Adding references

References Microsoft.entityframeworkcore and Microsoft.EntityFrameworkCore.SqlServer to projects DataAccess and webtest through NuGet

3. New EF Core context (Efdbcontext)
 Public class Efdbcontext:dbcontext    {        public efdbcontext (dbcontextoptions<efdbcontext> options) :base(options)        {                    }        publicgetset;}    }
4. Configure the startup entry for Efdbcontext

In the startup class of the Web project, find the Configureservices method and add the EF startup item, the first sentence of the following code:

 Public void configureservices (iservicecollection services)        {            services. Addentityframeworksqlserver (). Adddbcontext<EFDbContext> (Options and options). Usesqlserver (configuration.getconnectionstring ("SQL Server"));             // ADD Framework Services.             Services. Addapplicationinsightstelemetry (Configuration);            Services. Addmvc ();        }

Here are two places to note:

    • This method will be called when the project is started, and Efdbcontext will be registered with the ASP. NET Core's IOC, which can be injected directly into the Efdbcontext (below).
    • Configuration.getconnectionstring ("SQL Server") This is to read the configuration of the system, the system configuration in the Appsettings.json file, you need to manually add the configuration, after the completion of the addition is similar to:
{  "ConnectionStrings": {    "SQL Server": "Data source=localhost;initial catalog= Database-name;integrated Security=false; Persist Security Info=false; User Id=sa; Password=password "  },  " Logging ": {    false,    " LogLevel " : {      "Default": "Debug",      "System": "Information",      "Microsoft": " Information "    }}  }
5.WebAPI Controller

First, on the code ~

[Route ("api/address")] Public classaddresscontroller:controller{PrivateEfdbcontext _context;  PublicAddresscontroller (Efdbcontext context) {_context=context; } [Httpget,route ("GetAll")]     PublicIlist<address>GetAll () {varList= _context. Address.take (Ten).        ToList (); returnlist; }}

Now listen to me slowly.

    • First: [Route ("api/address")] This is used to define the public part of the API, this if you have WEBAPI development experience, this is very easy to understand, in Webapi, this will be written [Routeprefix ("Api/address" )]
    • Second, we see that efdbcontext is injected through the constructor, and this will use the information we have configured in the startup class above.
    • Next, the method getall the attribute tag [HttpGet] above defines the API's request predicate, the route ("GetAll") defines the address of the API, and finally, this address and the route above the controller together to determine the address of this API, In this example, the GetAll method eventually generates an API address of:/api/address/getall
    • Next, use the _context object for database operations, which is exactly the same as EF ~

At this point, my demo code is finished, directly F5 run, the browser manually hit an address/api/address/getall can access to the database in the first 10 data ~

Try. NET core-to build Webapi with. NET core + Entity FrameWork core (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.