四时宝库

程序员的知识宝库

ASP.NET Core 中文文档 第二章 指南(4.5)使用 SQL Server LocalDB

ApplicationDbContext类负责连接数据库并将Movie对象和数据记录进行映射。Startup.cs文件中,数据库上下文是在ConfigureServices方法中用Dependency Injection容器进行注册的。

// 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<ApplicationDbContext>(options => //手动高亮
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); //手动高亮

ASP.NET Core Configuration系统读取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 数据库的连接字符串。更多参考 Configuration。

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)

注意钥匙图标后面的 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<DbContextOptions<ApplicationDbContext>>))
 {
 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)这行设置断点,并开始调试

应用程序显示了被填充的数据.

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接