这段时间一个项目用到了mvc和webapi,然后一直对knockout比较感兴趣,就想着用这个框架做一个小实例。数据库采用的是sqlserver。话不多说,开始进行项目的步骤。
第一步:数据库的表创建。创建一个Employees员工表,具体字段见下图:
第二步:创建一个MVC项目,项目模板选择webapi。
第三步:在Model文件夹下新建一个ado.net实体数据模型,选择我们刚刚创建的employees的表,生成实体数据模型。
第四步:在controller文件夹下新建一个控制器,注意是包含读写操作和视图的API控制器,如下图
查看生成的代码如下
1 using System; 2 using System.Collections.Generic; 3 using System.Data; 4 using System.Data.Entity; 5 using System.Data.Entity.Infrastructure; 6 using System.Linq; 7 using System.Net; 8 using System.Net.Http; 9 using System.Web; 10 using System.Web.Http; 11 using DemoWebApi.Models; 12 13 namespace DemoWebApi.Controllers 14 { 15 public class EmployeeWebApiController : ApiController 16 { 17 private DemoDBEntities1 db = new DemoDBEntities1(); 18 19 // GET api/EmployeeWebApi 20 public IEnumerableGetEmployees() 21 { 22 return db.Employees.AsEnumerable(); 23 } 24 25 // GET api/EmployeeWebApi/5 26 public Employees GetEmployees(int id) 27 { 28 Employees employees = db.Employees.Find(id); 29 if (employees == null) 30 { 31 throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound)); 32 } 33 34 return employees; 35 } 36 37 // PUT api/EmployeeWebApi/5 38 public HttpResponseMessage PutEmployees(int id, Employees employees) 39 { 40 if (!ModelState.IsValid) 41 { 42 return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); 43 } 44 45 if (id != employees.EmployeeID) 46 { 47 return Request.CreateResponse(HttpStatusCode.BadRequest); 48 } 49 50 db.Entry(employees).State = EntityState.Modified; 51 52 try 53 { 54 db.SaveChanges(); 55 } 56 catch (DbUpdateConcurrencyException ex) 57 { 58 return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex); 59 } 60 61 return Request.CreateResponse(HttpStatusCode.OK); 62 } 63 64 // POST api/EmployeeWebApi 65 public HttpResponseMessage PostEmployees(Employees employees) 66 { 67 if (ModelState.IsValid) 68 { 69 db.Employees.Add(employees); 70 db.SaveChanges(); 71 72 HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, employees); 73 response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = employees.EmployeeID })); 74 return response; 75 } 76 else 77 { 78 return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); 79 } 80 } 81 82 // DELETE api/EmployeeWebApi/5 83 public HttpResponseMessage DeleteEmployees(int id) 84 { 85 Employees employees = db.Employees.Find(id); 86 if (employees == null) 87 { 88 return Request.CreateResponse(HttpStatusCode.NotFound); 89 } 90 91 db.Employees.Remove(employees); 92 93 try 94 { 95 db.SaveChanges(); 96 } 97 catch (DbUpdateConcurrencyException ex) 98 { 99 return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex); 100 } 101 102