Working with SQL Server LocalDB
https://docs.asp.net/en/latest/tutorials/first-mvc-app/working-with-sql.html
The ApplicationDbContext
class handles the task of connecting to the database and mapping Movie
objects to database records.
The database context is registered with the Dependency Injectioncontainer in the ConfigureServices
method in the Startup.cs file:
- public void ConfigureServices(IServiceCollection services)
- {
- // Add framework services.
- services.AddDbContext<ApplicationDbContext>(options =>
- options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
The ASP.NET Core Configuration 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 Configuration .
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<DbContextOptions<ApplicationDbContext>>()))
- {
- // 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.
Working with SQL Server LocalDB的更多相关文章
- ASP.NET Core 中文文档 第二章 指南(4.5)使用 SQL Server LocalDB
原文:Working with SQL Server LocalDB 作者:Rick Anderson 翻译: 魏美娟(初见) 校对: 孟帅洋(书缘).张硕(Apple).许登洋(Seay) Appl ...
- ASP.NET MVC 5 - 创建连接字符串(Connection String)并使用SQL Server LocalDB
您创建的MovieDBContext类负责处理连接到数据库,并将Movie对象映射到数据库记录的任务中.你可能会问一个问题,如何指定它将连接到数据库? 实际上,确实没有指定要使用的数据库,Entity ...
- ASP.NET MVC 5 学习教程:使用 SQL Server LocalDB
原文 ASP.NET MVC 5 学习教程:使用 SQL Server LocalDB 起飞网 ASP.NET MVC 5 学习教程目录: 添加控制器 添加视图 修改视图和布局页 控制器传递数据给视图 ...
- 009.Working with SQL Server LocalDB --【在sql server localdb 上操作数据】
Working with SQL Server LocalDB 在sql server localdb 上操作数据 2017-3-7 2 分钟阅读时长 本文内容 1.SQL Server Expres ...
- [转]ASP.NET MVC 5 - 创建连接字符串(Connection String)并使用SQL Server LocalDB
您创建的MovieDBContext类负责处理连接到数据库,并将Movie对象映射到数据库记录的任务中.你可能会问一个问题,如何指定它将连接到数据库? 实际上,确实没有指定要使用的数据库,Entity ...
- [.Net MVC] 使用SQL Server数据库代替LocalDb
之前开发的时候一直用的VS2013,所以数据库也用的LocalDb,这给开发带来很大便利.不过由于开发后还要进行部署,就改用了SQL Server 2012,这里总结下过程. 基本环境:VS2013, ...
- SQL Server 2012 LocalDB 管理之旅
SQL Server LocalDB能够最大限度地节省您的数据库管理精力,以便开发人员可以专注于开发数据库应用. 使用SqlLocalDB命令行管理LocalDB 为了方便管理,LocalDB提供了一 ...
- 通过 Docker Compose 组合 ASP NET Core 和 SQL Server
目录 Docker Compose 简介 安装 WebApi 项目 创建项目 编写Dockfile Web MVC 项目 创建项目 编写Dockfile 编写 docker-compose.yml文件 ...
- asp.net mvc entityframework sql server 迁移至 mysql方法以及遇到的问题
背景: 我原来的项目是asp.net mvc5 + entityframework 6.4 for sql server(localdb,sql server),现在需要把数据库切换成mysql,理论 ...
随机推荐
- web通信之跨文档通信 postMessage
index.html <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type&qu ...
- 实现Brush对象的五种图形
本实例将使用Graphics类绘制五种图形来分别演示SolidBrush.HatchBrush.TextureBrush.LinearGradientBrush.PathGradientBrush这五 ...
- Burn Down Chart(2018.5.28~2018.6.3)
任务安排 (2018.6.2 更新——前端总进度) (2018.6.3 更新——后端燃尽图) 娄雨禛[前端部分] 曾子轩[后端部分+燃尽图] 前端 齐天扬+刘鼎乾:设计两组页面,只要求框架和简单的 c ...
- 【Oracle】truncate分区表
分区表是生产中常用的一种表,它可以实现数据的按类存放,极大的提高了数据的查询及维护.当我们不需要某一分区的数据时,可以采用truncate来清空分区.实验如下: SQL)) partition by ...
- 使用Ajax验证用户名
Ajax是一项很重要的技术,下面简要举个例子,来解释如何使用Ajax.步骤如下:使用Ajax验证用户名使用文本框的onBlur事件 使用Ajax技术实现异步交互创建XMLHttpRequest对象通过 ...
- JAVA语言编程格式高级规范
作为一位开发人员,都要有严格的代码规范.为此我总结了一些代码规范案例. 目 录 1. 前言 2. 试用范围 3. JAVA命名规范-- 3.1 公共约定 3.2 Java文件.包 3.3 类.接口 ...
- Windows Phone 应用程序的生命周期(二)
一.App.xaml.cs /// <summary> /// Application 对象的构造函数. /// </summary> public App() { // 未捕 ...
- (转)C#开发微信门户及应用(2)--微信消息的处理和应答
http://www.cnblogs.com/wuhuacong/p/3614175.html 微信应用如火如荼,很多公司都希望搭上信息快车,这个是一个商机,也是一个技术的方向,因此,有空研究下.学习 ...
- spring3+quartz2
听说来自这里www.ydyrx.com 转载的: 最近公司要用定时任务,自己想着学习并完成任务,百度,google,360,必应,能用的搜索都用了,参差不齐,搞了一整天,也没找到一个好的例子.没办法, ...
- Android LinearLayout整个布局设置不可点击
1,activity的xml布局(布局中有个Button按钮,点击按钮弹出一个popupwindow ) <?xml version="1.0" encoding=" ...