zoukankan      html  css  js  c++  java
  • ASP.NET Core 中文文档 第二章 指南(4.5)使用 SQL Server LocalDB

    原文:Working with SQL Server LocalDB
    作者:Rick Anderson
    翻译: 魏美娟(初见)
    校对: 孟帅洋(书缘)张硕(Apple)许登洋(Seay)

    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()) 这行设置断点,并开始调试


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

    返回目录

  • 相关阅读:
    How to function call using 'this' inside forEach loop
    jquery.validate.unobtrusive not working with dynamic injected elements
    Difference between jQuery.extend and jQuery.fn.extend?
    Methods, Computed, and Watchers in Vue.js
    Caution using watchers for objects in Vue
    How to Watch Deep Data Structures in Vue (Arrays and Objects)
    Page: DOMContentLoaded, load, beforeunload, unload
    linux bridge
    linux bridge
    EVE-NG网卡桥接
  • 原文地址:https://www.cnblogs.com/dotNETCoreSG/p/aspnetcore-2_4_5-working-with-sql.html
Copyright © 2011-2022 走看看