在 ASP.NET Core中使用數(shù)據(jù)庫

2019-04-17 08:56 更新

查看或下載示例代碼如何下載)。

RazorPagesMovieContext 對象處理連接到數(shù)據(jù)庫并將 Movie 對象映射到數(shù)據(jù)庫記錄的任務(wù)。 在 Startup.cs 的 ConfigureServices 方法中向依賴關(guān)系注入容器注冊數(shù)據(jù)庫上下文:

C#
// This method gets called by the runtime. 
// Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        // This lambda determines whether user consent for non-essential cookies is 
        // needed for a given request.
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

    services.AddDbContext<RazorPagesMovieContext>(options =>
      options.UseSqlServer(
          Configuration.GetConnectionString("RazorPagesMovieContext")));
}

有關(guān) ConfigureServices 中使用的方法的詳細(xì)信息,請參閱:

ASP.NET Core 配置系統(tǒng)會讀取 ConnectionString。 為了進(jìn)行本地開發(fā),它會從 appsettings.json 文件獲取連接字符串。

生成代碼的數(shù)據(jù)庫名稱值 (Database={Database name}) 將并不不同。 名稱值是任意的。

JSON
{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "RazorPagesMovieContext": "Server=(localdb)\\mssqllocaldb;Database=RazorPagesMovieContext-1234;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

將應(yīng)用部署到測試或生產(chǎn)服務(wù)器時,可以使用環(huán)境變量將連接字符串設(shè)置為實際的數(shù)據(jù)庫服務(wù)器。有關(guān)詳細(xì)信息,請參閱配置。

SQL Server Express LocalDB

LocalDB 是輕型版的 SQL Server Express 數(shù)據(jù)庫引擎,以程序開發(fā)為目標(biāo)。 LocalDB 作為按需啟動并在用戶模式下運行的輕量級數(shù)據(jù)庫沒有復(fù)雜的配置。 默認(rèn)情況下,LocalDB 數(shù)據(jù)庫在 C:/Users/<user/> 目錄下創(chuàng)建 *.mdf 文件。

  • 從“視圖”菜單中,打開“SQL Server 對象資源管理器”(SSOX)。

    “視圖”菜單

  • 右鍵單擊 Movie 表,然后選擇“視圖設(shè)計器”:

    Movie 表上打開的上下文菜單

    設(shè)計器中打開的 Movie 表

請注意 ID 旁邊的密鑰圖標(biāo)。 默認(rèn)情況下,EF 為該主鍵創(chuàng)建一個名為 ID 的屬性。

  • 右鍵單擊 Movie 表,然后選擇“查看數(shù)據(jù)”:

    顯示表數(shù)據(jù)的打開的 Movie 表

設(shè)定數(shù)據(jù)庫種子

使用以下代碼在 Models 文件夾中創(chuàng)建一個名為 SeedData 的新類:

C#

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

namespace RazorPagesMovie.Models
{
    public static class SeedData
    {
        public static void Initialize(IServiceProvider serviceProvider)
        {
            using (var context = new RazorPagesMovieContext(
                serviceProvider.GetRequiredService<
                    DbContextOptions<RazorPagesMovieContext>>()))
            {
                // 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-2-12"),
                        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();
            }
        }
    }
}

如果 DB 中有任何電影,則會返回種子初始值設(shè)定項,并且不會添加任何電影。

C#

if (context.Movie.Any())
{
    return;   // DB has been seeded.
}

添加種子初始值設(shè)定項

在 Program.cs 中,修改 Main 方法以執(zhí)行以下操作:

  • 從依賴關(guān)系注入容器獲取數(shù)據(jù)庫上下文實例。
  • 調(diào)用 seed 方法,并將上下文傳遞給它。
  • Seed 方法完成時釋放上下文。

下面的代碼顯示更新后的 Program.cs 文件。

C#

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using RazorPagesMovie.Models;
using System;
using Microsoft.EntityFrameworkCore;

namespace RazorPagesMovie
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var host = CreateWebHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;

                try
                {
                    var context=services.
                        GetRequiredService<RazorPagesMovieContext>();
                    context.Database.Migrate();
                    SeedData.Initialize(services);
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService<ILogger<Program>>();
                    logger.LogError(ex, "An error occurred seeding the DB.");
                }
            }

            host.Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }
}

生產(chǎn)應(yīng)用不會調(diào)用 Database.Migrate。 它會添加到上面的代碼中,以防止在未運行 Update-Database 時出現(xiàn)以下異常:

SqlException:無法打開登錄請求的數(shù)據(jù)庫“RazorPagesMovieContext-21”。 登錄失敗。 用戶“用戶名”登錄失敗。

測試應(yīng)用

  • 刪除 DB 中的所有記錄。 可以使用瀏覽器中的刪除鏈接,也可以從 SSOX 執(zhí)行此操作

  • 強制應(yīng)用初始化(調(diào)用 Startup 類中的方法),使種子方法能夠正常運行。 若要強制進(jìn)行初始化,必須先停止 IIS Express,然后再重新啟動它。 可以使用以下任一方法來執(zhí)行此操作:

    • 右鍵單擊通知區(qū)域中的 IIS Express 系統(tǒng)任務(wù)欄圖標(biāo),然后點擊“退出”或“停止站點”:

      IIS Express 系統(tǒng)任務(wù)欄圖標(biāo)

      上下文菜單

      • 如果是在非調(diào)試模式下運行 VS 的,請按 F5 以在調(diào)試模式下運行。
      • 如果是在調(diào)試模式下運行 VS 的,請停止調(diào)試程序并按 F5。

應(yīng)用將顯示設(shè)定為種子的數(shù)據(jù):

在 Chrome 中打開的顯示電影數(shù)據(jù)的電影應(yīng)用程序

在下一教程中將對數(shù)據(jù)的展示進(jìn)行整理。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號