前言
本文将要完成在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}