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 Movieobjects 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
Movietable > 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
Movietable > 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
Startupclass) 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,理论 ...
随机推荐
- windows phone控件
常用控件: 包括: Button控件.CheckBox控件.HyperlinkButton控件.Iamege控件.ListBox控件.PasswordBox控件.ProgressBar控件.Radio ...
- VM虚拟机中Ubuntu中执行apt-get update失败的解决方法(可能有效)
首先确保虚拟机是连接网络的,可以用ping命令检测一下看是否连通网络.采用nat网络的时候确保服务是开的. 如果之前执行过apt-get update命令但是失败了,执行一下 rm -rf ...
- IOS 监控网络变化案例源码
随着移动网络升级:2G->3G->4G甚至相传正在研发的5G,网络速度是越来越快,但这流量也像流水一般哗哗的溜走. 网上不是流传一个段子:睡觉忘记关流量,第二天房子就归移动了! 这固然是一 ...
- CMMI评估流程
原文链接:http://www.cmmcn.com/new/cmmi-105.html 当前位置:首页 >> CMMI知识库 >> CMMI相关 >> CMMI评估 ...
- VTK初始化New返回Null问题
原文链接:http://www.cppblog.com/mythma/archive/2013/08/02/vtk-6-new-null.html 在使用VTK6.0时候,会遇到X::New()返回为 ...
- C# 判断字符串是否左包含
//测试字符串 左包含 //string str = "AAABBBCCC"; //char[] ss = str.ToArray(); //0-8 字符数组 //char[] s ...
- js 获取属性名称,再根据这个属性名获取值
if (result.success) { var obj = JSON.parse(result.data); var sltObj = document.getElementById(" ...
- Match 基因匹配 题解(From luoguBlog)
N<=20000!N2的LCS要原地爆炸. 去您妈的优化考场上有分就行TLE60真香嘿嘿嘿 然而这显然是个板子只不过像我这样见识短浅的蒟蒻不知道罢了 正解: 某大佬的博客 转化为lis后二分 复 ...
- wx 小程序开发---开发者工具使用
1:右侧详情界面 合法域名 都要在需要在小程序平台 配置合法域名 这样你的小程序请求的网址 才能通. 1.2如果自己的域名没有配置https 可以勾选为 不校验合法域名即可 (小程序官方规定 网址必须 ...
- 团体程序设计天梯赛-练习集-L1-036. A乘以B
L1-036. A乘以B 看我没骗你吧 —— 这是一道你可以在10秒内完成的题:给定两个绝对值不超过100的整数A和B,输出A乘以B的值. 输入格式: 输入在第一行给出两个整数A和B(-100 < ...