博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Working with SQL Server LocalDB
阅读量:6296 次
发布时间:2019-06-22

本文共 4907 字,大约阅读时间需要 16 分钟。

The ApplicationDbContext class handles the task of connecting to the database and mapping Movieobjects to database records.

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

public void ConfigureServices(IServiceCollection services)        {            // Add framework services.            services.AddDbContext
(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

The ASP.NET Core  system reads the ConnectionString.

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

{  "ConnectionStrings": {    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-MvcMovie-056c4c63-225a-436a-b9a8-a24628152dee;Trusted_Connection=True;MultipleActiveResultSets=true"  },  "Logging": {    "IncludeScopes": false,

 

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. See  .

 

SQL Server Express LocalDB

注意看之前的数据库连接,根据连接去找到对应的数据库

Server=(localdb)\\mssqllocaldb;Database=aspnet-MvcMovie-056c4c63-225a-436a-b9a8-a24628152dee;

LocalDB is a lightweight version of the SQL Server Express Database Engine that is targeted for program development. LocalDB starts on demand and runs in user mode, so there is no complex configuration. By default, LocalDB database creates “*.mdf” files in the C:/Users/<user> directory.

  • From the View menu, open SQL Server Object Explorer (SSOX).
  • Right click on the Movie table > View Designer

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

  • Right click on the Movie table > View Data

 

 

Seed the database

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

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
>())) { // 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(); } } }}

 

Notice if there are any movies in the DB, the seed initializer returns.

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

 

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

app.UseMvc(routes =>            {                routes.MapRoute(                    name: "default",                    template: "{controller=Home}/{action=Index}/{id?}");            });            SeedData.Initialize(app.ApplicationServices);

 

Test the app

  • Delete all the records in the DB. You can do this with the delete links in the browser or from SSOX.
  • Force the app to initialize (call the methods in the Startup class) so the seed method runs. To force initialization, IIS Express must be stopped and restarted. You can do this with any of the following approaches:
    • Right click the IIS Express system tray icon in the notification area and tap Exit or Stop Site
  • If you were running VS in non-debug mode, press F5 to run in debug mode
  • If you were running VS in debug mode, stop the debugger and press ^F5

 

If the database doesn’t initialize, put a break point on the line if (context.Movie.Any()) and start debugging.

 

The app shows the seeded data.

 

转载地址:http://ywmta.baihongyu.com/

你可能感兴趣的文章
Android 使用 ViewPager+RecyclerView+SmartRefreshLayout 实现顶部图片下拉视差效果
查看>>
Flutter之基础Widget
查看>>
写给0-3岁产品经理的12封信(第08篇)——产品运营能力
查看>>
ArcGIS Engine 符号自动化配置工具实现
查看>>
小程序 · 跳转带参数写法,兼容url的出错
查看>>
flutter error
查看>>
Flask框架从入门到精通之模型数据库配置(十一)
查看>>
10年重新出发
查看>>
2019年-年终总结
查看>>
聊聊elasticsearch的RoutingService
查看>>
让人抓头的Java并发(一) 轻松认识多线程
查看>>
从源码剖析useState的执行过程
查看>>
地包天如何矫正?
查看>>
中间件
查看>>
Android SharedPreferences
查看>>
css面试题
查看>>
Vue组建通信
查看>>
用CSS画一个带阴影的三角形
查看>>
前端Vue:函数式组件
查看>>
程鑫峰:1.26特朗.普力挺美元力挽狂澜,伦敦金行情分析
查看>>