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.
相关文章
- SQL Server-聚焦深入理解死锁以及避免死锁建议(三十三)
- SQL Server-聚焦聚集索引对非聚集索引的影响(四)
- SQL SERVER 2016 AlwaysOn 无域集群+负载均衡搭建与简测
- INF: How SQL Server Compares Strings with Trailing Spaces
- SQL Server loop - how do I loop through a set of records
- is-a,has-a,like-a是什么 sql server中,N''表示什么意思? 关于SQL SERVER的N前缀的理解
- C#构造方法(函数) C#方法重载 C#字段和属性 MUI实现上拉加载和下拉刷新 SVN常用功能介绍(二) SVN常用功能介绍(一) ASP.NET常用内置对象之——Server sql server——子查询 C#接口 字符串的本质 AJAX原生JavaScript写法
- SQL Server 占用内存太高,查找占用内存高以及影响其性能的sql语句及解决方法
- 基于C#+SQL Server实现(Web)学生选课管理系统【100010309】
- sql server 小技巧(8) visual studio 2013里使用Sql server compact 4.0及发布问题处理
- SQL Server-语句类别、数据库范式、系统数据库组成
- SQL Server的分页优化及Row_Number()分页存在的问题
- SQL Server SSPI handshake failed报错,sql server修改windows账户密码的影响,sql server订阅发布客户端访问一直报错
- 【基本优化实践】【1.7】sql server统计信息优化
- sql server代理服务无法启动(SQL Agent):OpenSQLServerInstanceRegKey:GetRegKeyAccessMask failed (reason: 2).
- (4.11)sql server内存使用
- (3.15)常用知识-sql server分页查询
- SQL Server Profiler 跟踪某个数据库某张表sql语句
- How to Kill All Processes That Have Open Connection in a SQL Server Database[关闭数据库链接 最佳方法] -摘自网络
- sql server-SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON
- sql server 加锁 WITH(TABLOCK)
- sql server 加锁 WITH(TABLOCK)
- 微软加入Linux基金会以后 公开Linux版本SQL Server