Building applications using Web APIs and EntityFramework in ASP.

Source: Internet
Author: User

A recent project technology pre-study: Using Web APIs and EntityFramework in the ASP. NET MVC framework, building a basic architecture, and implementing the underlying CRUD application.

The following are the detailed steps.

The first step

Create a data table in the database with the table named Customer, see:

Step Two
    • Open Visual Studio and create a new project.

    • Select ' ASP. NET Web application ', named ' WebApi '.

    • We will create a ' Web API ', select ' Web API ' in the template and click ' OK '.

      Step Three

      Next I'm going to add a class.

    • Right-click on this Web API project and add an ' ADO Data Model '.

    • Add ' EF Designer from database ' and click ' Next '.

    • Add a new connection in the Configuration window, enter the server name, select the database, and click ' OK '.

    • Click ' Next ' to select the data table to associate with.

    • Click ' Finish '.

      Fourth Step

      The job now is to add a controller to the WEP API.

    • Right-Select the ' Controllers ' folder.

    • Select ' MVC5 Controller with views, using Entity Framework '.

    • Click ' Add '.

    • Select the data model class customer, and select the database context class file, in this case systemtestentity.

    • Set the controller name to Customerscontroller and click ' Add '.

      When the above operation is complete, CustomerController.cs is automatically generated.

CustomerController.cs

Using System.Data.Entity;  Using System.Data.Entity.Infrastructure;  Using System.Linq;  Using System.Net;  Using System.Web.Http;  Using System.Web.Http.Description;    Using Crudwebapiexam.models; Namespace Crudwebapiexam.controllers {public class Customerscontroller:apicontroller {private Syst            Emtestentities db = new systemtestentities (); Get:api/customers public iqueryable<customer> GetCustomer () {return db.          Customer; }//GET:API/CUSTOMERS/5 [Responsetype (typeof (Customer)]) public Ihttpactionresult Getcustom ER (int id) {Customer customer = db.              Customer.find (ID);              if (customer = = null) {return NotFound ();          } return Ok (customer); }//PUT:API/CUSTOMERS/5 [Responsetype (typeof (void))] public Ihttpactionresult Putcustomer (i NT ID, customer customer) {if (!              Modelstate.isvalid) {return badrequest (modelstate); } if (id! = Customer.              CustomerId) {return badrequest (); } db. Entry (Customer).              state = entitystate.modified; try {db.              SaveChanges (); } catch (Dbupdateconcurrencyexception) {if (!                  Customerexists (ID)) {return NotFound ();                  } else {throw;          }} return StatusCode (httpstatuscode.nocontent); }//Post:api/customers [Responsetype (typeof (Customer)]) public Ihttpactionresult Postcustom ER (Customer customer) {if (!     Modelstate.isvalid) {return badrequest (modelstate);         } db.              Customer.add (customer); Db.               SaveChanges (); Return Createdatroute ("Defaultapi", new {id = customer.          CustomerId}, customer); }//DELETE:API/CUSTOMERS/5 [Responsetype (typeof (Customer)]) public Ihttpactionresult DELETE Customer (int id) {Customer customer = db.              Customer.find (ID);              if (customer = = null) {return NotFound (); } db.              Customer.remove (customer); Db.              SaveChanges ();          Return Ok (Customer);                  } protected override void Dispose (bool disposing) {if (disposing) { Db.              Dispose (); } base.          Dispose (disposing); } private bool Customerexists (int id) {return db.          Customer.count (E = E.customerid = = id) > 0;   }      }  }

Run this WEB API project and you will see the following results

Fifth Step

So far, the Web API has been built successfully. Next we need to add a consumer object for this Web API service, which is the MVC project to be covered in this article.

    • To first add a model class, we can directly take the customer class above. Right click on the Models folder, add Class and name. In this case, I named Customer.cs directly.
      Customer.cs
using System;  using System.ComponentModel.DataAnnotations;    namespace MVCPersatantion.Models  {      public class Customer      {          [Display(Name = "CustomerId")]          public int CustomerId { get; set; }          [Display(Name = "Name")]          public string Name { get; set; }          [Display(Name = "Address")]          public string Address { get; set; }          [Display(Name = "MobileNo")]          public string MobileNo { get; set; }          [Display(Name = "Birthdate")]          [DataType(DataType.Date)]          public DateTime Birthdate { get; set; }          [Display(Name = "EmailId")]          public string EmailId { get; set; }              }   }  
    • After the customer class is added, the next step is to add a ViewModel folder and create a new CustomerViewModel.cs file inside.
      CustomerViewModel.cs
using MVCPersatantion.Models;    namespace MVCPersatantion.ViewModel  {      public class CustomerViewModel      {          public Customer customer { get; set; }      }  }
Sixth step

I have added a class to consume the Web API service, and now I need to add a client class.

    • Right click on the Models folder and add Class file CustomerClient.cs.
      CustomerClient.cs
Using System;  Using System.Collections.Generic;  Using System.Net.Http;    Using System.Net.Http.Headers; Namespace Mvcpersatantion.models {public class Customerclient {private String base_url = "Http://loc            alhost:30110/api/";  Public ienumerable<customer> FindAll () {try {HttpClient client                  = new HttpClient (); Client.                  baseaddress = new Uri (base_url); Client.                  DEFAULTREQUESTHEADERS.ACCEPT.ADD (New Mediatypewithqualityheadervalue ("Application/json")); Httpresponsemessage response = client. Getasync ("Customers").                    Result; if (response. Issuccessstatuscode) return response. Content.readasasync<ienumerable<customer>> ().                  Result;              return null;              } catch {return null; }} public Customer find (int id) {             try {HttpClient client = new HttpClient (); Client.                  baseaddress = new Uri (base_url); Client.                  DEFAULTREQUESTHEADERS.ACCEPT.ADD (New Mediatypewithqualityheadervalue ("Application/json")); Httpresponsemessage response = client. Getasync ("customers/" + ID).                    Result; if (response. Issuccessstatuscode) return response. Content.readasasync<customer> ().                  Result;              return null;              } catch {return null; }} public bool Create (customer customer) {try {Ht                  Tpclient client = new HttpClient (); Client.                  baseaddress = new Uri (base_url); Client.                  DEFAULTREQUESTHEADERS.ACCEPT.ADD (New Mediatypewithqualityheadervalue ("Application/json")); Httpresponsemessage response = client. PostasjSonasync ("Customers", customer).                  Result; return response.              Issuccessstatuscode;              } catch {return false; }} public bool Edit (customer customer) {try {Http                  Client client = new HttpClient (); Client.                  baseaddress = new Uri (base_url); Client.                  DEFAULTREQUESTHEADERS.ACCEPT.ADD (New Mediatypewithqualityheadervalue ("Application/json")); Httpresponsemessage response = client. Putasjsonasync ("customers/" + customer. CustomerId, customer).                  Result; return response.              Issuccessstatuscode;              } catch {return false; }} public bool Delete (int id) {try {HttpClient cl                  ient = new HttpClient (); Client.           baseaddress = new Uri (base_url);       Client.                  DEFAULTREQUESTHEADERS.ACCEPT.ADD (New Mediatypewithqualityheadervalue ("Application/json")); Httpresponsemessage response = client. Deleteasync ("customers/" + ID).                  Result; return response.              Issuccessstatuscode;              } catch {return false; }          }      }  }

Careful friends may have discovered that there is some duplication of code in my Code. In practical applications we can extract the common code so that it can be used anywhere. In order to clarify the process here, I wrote some repetitive code.

Let's look at the first line private string Base_URL = "http://localhost:50985/api/" , this base_url is the service address of the Web API.

You can then write the business logic for INSERT, Update, Delete, select.

Seventh Step

Right-click the Controllers folder and add a method called the customer controller to add the service client call.

Using System;  Using System.Collections.Generic;  Using System.Linq;  Using System.Web;  Using SYSTEM.WEB.MVC;  Using Mvcpersatantion.models;    Using Mvcpersatantion.viewmodel; Namespace Mvcpersatantion.controllers {public class Customercontroller:controller {//Get:custome              R public ActionResult Index () {customerclient CC = new Customerclient ();               Viewbag.listcustomers = Cc.findall ();          return View ();          } [HttpGet] public ActionResult Create () {return View ("create");  } [HttpPost] public actionresult Create (Customerviewmodel CVM) {customerclient CC              = new Customerclient (); Cc.              Create (Cvm.customer);          Return redirecttoaction ("Index");              } public actionresult Delete (int id) {Customerclient CC = new Customerclient (); Cc. Delete (ID);             Return redirecttoaction ("Index"); } [HttpGet] public actionresult Edit (int id) {Customerclient CC = new CUSTOMERCLI              ENT ();              Customerviewmodel CVM = new Customerviewmodel ();              Cvm.customer = Cc.find (ID);          Return View ("Edit", CVM);  } [HttpPost] public actionresult Edit (Customerviewmodel CVM) {customerclient CC =              New Customerclient (); Cc.              Edit (Cvm.customer);          Return redirecttoaction ("Index");   }      }  }
Eighth step
    • Create a View page index.cshtml.

    • Add code to the index page.
      Index.cshtml

@{viewbag.title = "Index";} 
    • Add new data module create.

    • Add the Create method to the customer controller, adding create.cshtml to the view.

Create.cshtml

@model webapimvc.viewmodel.customerviewmodel@{viewbag.title = "Create";} 
    • Add modify Data Module edit.

    • Add the Edit method to the customer controller, adding edit.cshtml to the view.

Edit.cshtml

@{viewbag.title = "Edit";} @model webapimvc.viewmodel.customerviewmodel

The final project code is complete. Let's try to run the project at this time. But it's also important to note that we have to run both the Web API and the MVC project. What do we do? In fact, as long as the project properties are set.

    • Right-click the solution and select Properties.

    • Next in the Startup Project option, select 多项目启动 , Action set up two items in the same time to start.

    • Run the project and look at the results of the CRUD operations execution.

Select

Insert

Update

Delete

This is the entire technology pre-research process, the end of this article provides code download.

Rhymes
Blog Address: http://www.cnblogs.com/yayazi/
This address: http://www.cnblogs.com/yayazi/p/8444054.html
Disclaimer: This blog original text allows reprint, reprint must retain this paragraph statement, and in the article page obvious location to give the original link.
SOURCE Download: Https://github.com/daivven/WebApiMVC

PS: I recently planned to change jobs, the target location in Wuhan, the target position. NET software engineer, expect a monthly salary of more than 12k, after the Spring Festival can participate in the interview. Do you have a suitable post recommendation, private messages I can send resume, beg inside push wow ~

Build applications in ASP. NET MVC using Web APIs and EntityFramework

Related Article

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.