009.Working with SQL Server LocalDB --【在sql server localdb 上操做數據】

索引:html

目錄索引sql

Working with SQL Server LocalDB數據庫

在sql server localdb 上操做數據express

2017-3-7 2 分鐘閱讀時長 json

本文內容服務器

1.SQL Server Express LocalDBmvc

SQL Server Express LocalDB  sql server 的一個簡化免費版本app

2.Seed the databaseide

初始化數據庫的初始表數據測試

By Rick Anderson

The MvcMovieContext object handles the task of connecting to the database and mapping Movie objects to database records.

MvcMovieContext 對象處理了連接數據庫與映射Movie 對象到表記錄的任務.

The database context is registered with the Dependency Injection container in the ConfigureServices method in the Startup.cs file:

DB上下文在Startup.cs 文件的ConfigureServices 方法中被註冊到了DI容器中:

 1 public void ConfigureServices(IServiceCollection services)
 2 
 3 {
 4 
 5     // Add framework services.
 6 
 7     services.AddMvc();
 8 
 9  
10 
11     services.AddDbContext<MvcMovieContext>(options =>
12 
13             options.UseSqlServer(Configuration.GetConnectionString("MvcMovieContext")));
14 
15 }
C# code

The ASP.NET Core Configuration system reads the ConnectionString.

Asp.net core 的配置系統讀取了ConnectionString 的配置的值。

For local development, it gets the connection string from the appsettings.json file:

對於本地開發,它從appsettings.json 文件獲取連接字符串的值:

1 "ConnectionStrings": {
2 
3   "MvcMovieContext": "Server=(localdb)\\mssqllocaldb;Database=MvcMovieContext-20613a4b-deb5-4145-b6cc-a5fd19afda13;Trusted_Connection=True;MultipleActiveResultSets=true"
4 
5 }
JSON Code

When you deploy the app to a test or production server, you can use an environment variable or another approach to set the connection string to a real SQL Server.

當你將應用部署到一個測試或生產服務器,你能夠使用環境變量或其它的方法來設置一個真實的db連接字符串的值。

See Configuration for more information.

查看Configuration 獲取更多信息。

SQL Server Express LocalDB

(一個簡化的免費的輕量的sql server 版本)

LocalDB is a lightweight version of the SQL Server Express Database Engine that is targeted for program development.

LocalDB 是 SQL Server Express Database Engine 的一個輕量版本,目的是本地的程序開發。

LocalDB starts on demand and runs in user mode, so there is no complex configuration.

LocalDB 以用戶模式直接開始查詢便可,所以沒有複雜的配置。

By default, LocalDB database creates "*.mdf" files in the C:/Users/<user> directory.

默認狀況下,LocalDB 會在C:/Users/<user> 文件夾下建立"*.mdf" 數據庫文件。

  • From the View menu, open SQL Server Object Explorer (SSOX).

View  菜單,打開 SQL Server Object Explorer

  • Right click on the Movie table > View Designer

右擊 Movie  表,點擊  > View Designer 菜單

Note the key icon next to ID. By default, EF will make a property named ID the primary key.

注意PK圖標在ID 字段旁邊,EF默認會使用ID作爲一個PK。

  • Right click on the Movie table > View Data

右擊 Movie 表,選擇 > View Data 菜單

Seed the database

向數據庫初始化值

Create a new class named SeedData in the Models folder. Replace the generated code with the following:

Models 文件夾下新建一個名爲SeedData 類,用下面的代碼替換掉自動生成的代碼:

  1 using Microsoft.EntityFrameworkCore;
  2 
  3 using Microsoft.Extensions.DependencyInjection;
  4 
  5 using System;
  6 
  7 using System.Linq;
  8 
  9  
 10 
 11 namespace MvcMovie.Models
 12 
 13 {
 14 
 15     public static class SeedData
 16 
 17     {
 18 
 19         public static void Initialize(IServiceProvider serviceProvider)
 20 
 21         {
 22 
 23             using (var context = new MvcMovieContext(
 24 
 25                 serviceProvider.GetRequiredService<DbContextOptions<MvcMovieContext>>()))
 26 
 27             {
 28 
 29                 // Look for any movies.
 30 
 31                 if (context.Movie.Any())
 32 
 33                 {
 34 
 35                     return;   // DB has been seeded
 36 
 37                 }
 38 
 39  
 40 
 41                 context.Movie.AddRange(
 42 
 43                      new Movie
 44 
 45                      {
 46 
 47                          Title = "When Harry Met Sally",
 48 
 49                          ReleaseDate = DateTime.Parse("1989-1-11"),
 50 
 51                          Genre = "Romantic Comedy",
 52 
 53                          Price = 7.99M
 54 
 55                      },
 56 
 57  
 58 
 59                      new Movie
 60 
 61                      {
 62 
 63                          Title = "Ghostbusters ",
 64 
 65                          ReleaseDate = DateTime.Parse("1984-3-13"),
 66 
 67                          Genre = "Comedy",
 68 
 69                          Price = 8.99M
 70 
 71                      },
 72 
 73  
 74 
 75                      new Movie
 76 
 77                      {
 78 
 79                          Title = "Ghostbusters 2",
 80 
 81                          ReleaseDate = DateTime.Parse("1986-2-23"),
 82 
 83                          Genre = "Comedy",
 84 
 85                          Price = 9.99M
 86 
 87                      },
 88 
 89  
 90 
 91                    new Movie
 92 
 93                    {
 94 
 95                        Title = "Rio Bravo",
 96 
 97                        ReleaseDate = DateTime.Parse("1959-4-15"),
 98 
 99                        Genre = "Western",
100 
101                        Price = 3.99M
102 
103                    }
104 
105                 );
106 
107                 context.SaveChanges();
108 
109             }
110 
111         }
112 
113     }
114 
115 }
C# Code

If there are any movies in the DB, the seed initializer returns and no movies are added.

若是數據庫中有數據記錄,就會直接返回,若是沒有就會添加這些初始數據。

1 if (context.Movie.Any())
2 
3 {
4 
5     return;   // DB has been seeded.
6 
7 }
C# Code

Add the seed initializer to the end of the Configure method in the Startup.cs file:

把數據初始化類添加到Startup.cs 文件的Configure  方法的最後一行:

 1             app.UseStaticFiles();
 2 
 3             app.UseMvc(routes =>
 4 
 5             {
 6 
 7                 routes.MapRoute(
 8 
 9                     name: "default",
10 
11                     template: "{controller=Home}/{action=Index}/{id?}");
12 
13             });
14 
15  
16 
17             SeedData.Initialize(app.ApplicationServices);
18 
19         }
20 
21     }
22 
23 }
C# Code

Test the app

測試應用

  • Delete all the records in the DB. You can do this with the delete links in the browser or from SSOX.

要刪除db中的全部數據記錄,你能夠在 SSOX 中點擊刪除連接便可。

  • Force the app to initialize (call the methods in the Startup class) so the seed method runs.

強制應用初始化,在 Startup  類中seed 方法會被執行。

To force initialization, IIS Express must be stopped and restarted. You can do this with any of the following approaches:

爲了強制初始化,iis express 必須重啓一下。你能夠使用如下方法的任一種來作到:

  • Right click the IIS Express system tray icon in the notification area and tap Exit or Stop Site

右擊系統托盤上通知區域的iis圖標,並點擊 Exit or Stop Site

  • If you were running VS in non-debug mode, press F5 to run in debug mode

若是你運行vs在非調試模式,按F5運行進入調試模式

  • If you were running VS in debug mode, stop the debugger and press F5

若是你運行vs在調試模式,中止調試並按下F5

The app shows the seeded data.

應用顯示出初始化後的數據: 

 

 

 

 

                                         蒙

                                    2017-08-14 15:22 週一

相關文章
相關標籤/搜索