原文:
作者: 翻译: 校对: 、、ApplicationDbContext
类负责连接数据库并将 Movie
对象和数据记录进行映射。 Startup.cs 文件中,数据库上下文是在 ConfigureServices
方法中用 容器进行注册的。
// This method gets called by the runtime. Use this method to add services to the container.public void ConfigureServices(IServiceCollection services){ // Add framework services. services.AddDbContext(options => //手动高亮 options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); //手动高亮
ASP.NET Core 系统读取 ConnectionString
。在本地开发模式下,它会从 appsettings.json 文件中获取连接字符串。
{ "ConnectionStrings": { "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-MvcMovie-7db2893b-375e-48bd-86a3-bb9779b72ebe;Trusted_Connection=True;MultipleActiveResultSets=true" //手动高亮 }, "Logging": { "IncludeScopes": false,
当你部署应用程序到测试服务器或者生产服务器时,你可以使用环境变量或者另一种方法来设置实际 SQL Server 数据库的连接字符串。更多参考 。
SQL Server Express LocalDB
LocalDB是针对程序开发阶段使用的一个SQL Server Express轻量级版本的数据库引擎。 因为LocalDB在用户模式下启动、执行,所以它没有复杂的配置。默认情况下,LocalDB数据库创建的 “*.mdf” 文件在 C:/Users/<user> 目录下。
从 View 菜单中,打开SQL Server对象资源管理器(SQL Server Object Explorer ,(SSOX)).
Movie
表 > 视图设计器(View Designer)![959753-20160617124233495-612002243.png](https://images2015.cnblogs.com/blog/959753/201606/959753-20160617124233495-612002243.png)
![959753-20160617124309417-1548004351.png](https://images2015.cnblogs.com/blog/959753/201606/959753-20160617124309417-1548004351.png)
ID
。默认情况下,EF将命名为 ID
的属性作为主键。 - 右击
Movie
表 > 查看数据(View Data)
填充数据库
在 Models 文件夹中创建一个名叫 SeedData
的新类。用以下代码替换生成的代码。
using Microsoft.EntityFrameworkCore;using Microsoft.Extensions.DependencyInjection;using MvcMovie.Data;using System;using System.Linq;namespace MvcMovie.Models{ public static class SeedData { public static void Initialize(IServiceProvider serviceProvider) { using (var context = new ApplicationDbContext( serviceProvider.GetRequiredService>())) { if (context.Movie.Any()) { return; // DB has been seeded } context.Movie.AddRange( new Movie { Title = "When Harry Met Sally", ReleaseDate = DateTime.Parse("1989-1-11"), Genre = "Romantic Comedy", Price = 7.99M }, new Movie { Title = "Ghostbusters ", ReleaseDate = DateTime.Parse("1984-3-13"), Genre = "Comedy", Price = 8.99M }, new Movie { Title = "Ghostbusters 2", ReleaseDate = DateTime.Parse("1986-2-23"), Genre = "Comedy", Price = 9.99M }, new Movie { Title = "Rio Bravo", ReleaseDate = DateTime.Parse("1959-4-15"), Genre = "Western", Price = 3.99M } ); context.SaveChanges(); } } }}
注意,如果数据库上下文中存在 movies,填充初始化器返回。
if (context.Movie.Any()) { return; // DB has been seeded //手动高亮 }
在 Startup.cs 文件中的 Configure
方法最后添加填充初始化器。
app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); SeedData.Initialize(app.ApplicationServices); //手动高亮}
测试应用程序
- 删除数据库中的所有记录。你可以直接在浏览器中点击删除链接或者在 SSOX(SQL Server对象资源管理器)中做这件事。
- 强制应用程序初始化(在
Startup
类中调用方法),这样填充方法会自动运行。为了强制初始化,IIS Express必须先停止,然后重新启动。可以用下列的任何一个方法来实现:
注意
如果是数据库没有初始化,在if (context.Movie.Any())
这行设置断点,并开始调试
![959753-20160617130826542-401827998.png](https://images2015.cnblogs.com/blog/959753/201606/959753-20160617130826542-401827998.png)