zoukankan      html  css  js  c++  java
  • 【Web API系列教程】3.3 — 实战:处理数据(建立数据库)

     前言

    本文将要完成在EF上使用Code First Migration建立数据库

     修改web..config中数据库连接字符串为本地数据库  .   其他默认

     在VS中工具目录下选择NuGet包管理器,选择程序包管理器控制台,

     在控制台窗口下输入命令

    1  Enable-Migrations -ContextTypeName BookService.Models.BookServiceContext

     命令后会添加一个名为Migrations的文件夹到你的项目中,并添加一个名为Configuration.cs的代码文件

    打开Configuration.cs,添加以下代码

    1 using BookService.Models;

    然后添加以下代码到Configuration.Seed方法:

     1 protected override void Seed(BookService.Models.BookServiceContext context)
     2 {
     3     context.Authors.AddOrUpdate(x => x.Id,
     4         new Author() { Id = 1, Name = "Jane Austen" },
     5         new Author() { Id = 2, Name = "Charles Dickens" },
     6         new Author() { Id = 3, Name = "Miguel de Cervantes" }
     7         );
     8 
     9     context.Books.AddOrUpdate(x => x.Id,
    10         new Book() { Id = 1, Title = "Pride and Prejudice", Year = 1813, AuthorId = 1, 
    11             Price = 9.99M, Genre = "Comedy of manners" },
    12         new Book() { Id = 2, Title = "Northanger Abbey", Year = 1817, AuthorId = 1, 
    13             Price = 12.95M, Genre = "Gothic parody" },
    14         new Book() { Id = 3, Title = "David Copperfield", Year = 1850, AuthorId = 2, 
    15             Price = 15, Genre = "Bildungsroman" },
    16         new Book() { Id = 4, Title = "Don Quixote", Year = 1617, AuthorId = 3, 
    17             Price = 8.95M, Genre = "Picaresque" }
    18         );
    19 }

    在Package Manager Console窗口,键入以下命令:

    1 Add-Migration Initial  //创建数据库到本地
    2 Update-Database   //执行那些代码

     重新编译并运行程序 

    显示数据

     API小结

        获取数据    GET   api/authors  获取所有Author信息

                          GET   api/authors/{id}   根据id获取Author信息

        插入数据    POST  api/authors

        修改数据    PUT    api/authors/{id}

        删除数据    DELETE  /api/authors/{id}

        

  • 相关阅读:
    【Feature】使用Feature导入WebPart
    千万别动SharePoint数据库
    【PS】使用PowerShell创建WinForm程序(转载)
    【WebServices】调用 SharePoint WebServices 注意事项
    【转载】十一种Web网站程序性能测试工具介绍
    【List Event Receivers】区分自定义“事件处理”功能的两种部署方式
    [转] SharePoint Server 2007 页面模型
    第一天 从此在这记录学习C++的点点滴滴
    《C++ Primer》第7章 函数
    Emacs 自动填充头文件
  • 原文地址:https://www.cnblogs.com/3309-whp/p/9407139.html
Copyright © 2011-2022 走看看