天天看點

vs2015中使用預設的localdb建立資料庫并實作增删查改(結合WebAPI)

本文主要參考官方文檔Using Web API 2 with Entity Framework 6和Enabling CRUD Operations in ASP.NET Web API 1。webapi2和webapi1在使用localdb上差别不大,操作過程是一樣的。

LocalDB簡介

本文用到的主要軟體:visual studio 2015、webapi2、localdb(version 2014)以及entity framework

第一步——添加localdb連接配接

建立一個webapi項目(步驟參考),若是勾選“individual authentication”,則項目會自動生成account authentication API,預設使用membership database,該項目可不用驗證,也不用在azure上釋出。然後在Web.config的<connectionStrings></connectionStrings> 中添加localdb連接配接代碼,如下:

<connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-TestWebAPI-20180410113854.mdf;Initial Catalog=aspnet-TestWebAPI-20180410113854;Integrated Security=True"
         providerName="System.Data.SqlClient" />
    <add name="ProductDBContext" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Products-20180410113854.mdf;Initial Catalog=Products-20180410113854;MultipleActiveResultSets=True;Integrated Security=True"
         providerName="System.Data.SqlClient" />
  </connectionStrings>
           

第一個connectionString是勾選individual authentication預設生成的,可不用;第二個是我們手動添加的,name不要随意取,須符合DBContext,不然找不到資料庫(随意取也行,官方文檔就使用了另外一種連接配接方式,但本質都是一樣的),Data Source因為vs2015預設localdb是2014版本的,是以選擇MSSQLLocalDB,2012版本則選擇v11.0.0;AttachDbFilename預設會在項目APP_Data檔案夾中生成對應的mdf檔案(資料庫檔案),其他參數可自行更改,Initial Catalog名稱任取。到此localdb連接配接即添加完成。

第二步——添加models和controllers

在Models和Controllers檔案夾中添加你需要的model和controller,modal建立實體類,controller用來寫CRUD API(增删查改);然後在實體類後面添加資料庫映射,建立DBContext:

vs2015中使用預設的localdb建立資料庫并實作增删查改(結合WebAPI)

第三步——生成資料庫和表

步驟見Use Code First Migrations to Seed the Database

第四步——在controller中寫增删查改API

代碼如下:

//[Authorize(Roles = "Administrator")]
    public class AdminController : ApiController
    {
        private OrdersContext db = new OrdersContext();//此處改成自己建立的localdb連接配接name

        // GET api/Admin
        public IEnumerable<Product> GetProducts()
        {
            return db.Products.AsEnumerable();
        }

        // GET api/Admin/5
        public Product GetProduct(int id)
        {
            Product product = db.Products.Find(id);
            if (product == null)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
            }

            return product;
        }

        // PUT api/Admin/5
        public HttpResponseMessage PutProduct(int id, Product product)
        {
            if (ModelState.IsValid && id == product.Id)
            {
                db.Entry(product).State = EntityState.Modified;

                try
                {
                    db.SaveChanges();
                }
                catch (DbUpdateConcurrencyException)
                {
                    return Request.CreateResponse(HttpStatusCode.NotFound);
                }

                return Request.CreateResponse(HttpStatusCode.OK);
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }
        }

        // POST api/Admin
        public HttpResponseMessage PostProduct(Product product)
        {
            if (ModelState.IsValid)
            {
                db.Products.Add(product);
                db.SaveChanges();

                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, product);
                response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = product.Id }));
                return response;
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }
        }

        // DELETE api/Admin/5
        public HttpResponseMessage DeleteProduct(int id)
        {
            Product product = db.Products.Find(id);
            if (product == null)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            db.Products.Remove(product);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            return Request.CreateResponse(HttpStatusCode.OK, product);
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
           

如果上述代碼中PUT即更新操作出現400 bad request錯誤,可試着将PUT的代碼更換成:

//PUT: /api/products/id
        public Boolean Put(int id, [FromBody]Product product)
        {
            var item = db.Tasks.SingleOrDefault(s => s.Id == id);

            if (item == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
                //return false;
            }
            else
            {
                item.Name = product.Name;
                item.NodeId = product.NodeId;
                item.NodeInfo = product.NodeInfo;
                item.Category = product.Category;
                item.TaskType = product.TaskType;
                item.Price = product.Price;
                item.Id = id;

                db.Entry(item).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();
                return true;
            }
        }
           

部落客在寫webapi和資料庫的時候有時會出現莫名其妙的錯誤,比如上面這個,官方給出的PUT API的代碼明明是對的,但是實際測試時老是報400 bad request error,後來換成我這個代碼就好了,讀者如果遇到和我一樣的情況可以試試。到此就可以使用ajax來測試web api進行增删查改了,本文僅供參考。

繼續閱讀