显示 / 隐藏目录

使用 SQLite

作者 Rick Anderson

翻译 谢炀(Kiler)

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

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();

    services.AddDbContext<MvcMovieContext>(options =>
            options.UseSqlite("Data Source=MvcMovie.db"));

}

SQLite

SQLite 官方网站的自我描述

SQLite 是一个独立的、高可用的、嵌入式的、功能齐全的 SQL 数据库引擎。SQLite 是在世界上使用的最广泛 SQL 数据库引擎。

有很多可以下载的第三方的管理和查看 SQLite 数据库工具。 下图中的是 DB Browser for SQLite。如果你有其他熟悉 SQLite 工具,请留言介绍一下它的优点。

SQLite DB Browser 工具显示 movie 数据

填充数据库

在 Models 文件夹中创建一个名叫 SeedData 的新类。用以下代码替换生成的代码。

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;

namespace MvcMovie.Models
{
    public static class SeedData
    {
        public static void Initialize(IServiceProvider serviceProvider)
        {
            using (var context = new MvcMovieContext(
                serviceProvider.GetRequiredService<DbContextOptions<MvcMovieContext>>()))
            {
                // Look for any movies.
                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=Movies}/{action=Index}/{id?}");
    });
     
    DBinitialize.EnsureCreated(app.ApplicationServices);
    SeedData.Initialize(app.ApplicationServices);
}

测试一下

删除数据库中的所有记录 (这样 Seed 方法就会运行)。停止然后重新启动应用程序来填充数据库。

应用程序显示了填充数据。

MVC Movie application open browser showing movie data

上一节 - 添加模型 下一节 - 控制器与视图

  • 改进文档
  • 0 评论
返回顶部 Copyright © 2015-2017 Microsoft
Generated by DocFX