索引:

目录索引

Working with SQL Server LocalDB

在sql server localdb 上操作数据

2017-3-7 2 分钟阅读时长

本文内容

1.SQL Server Express LocalDB

SQL Server Express LocalDB  sql server 的一个简化免费版本

2.Seed the database

初始化数据库的初始表数据

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容器中:

 public void ConfigureServices(IServiceCollection services)

 {

     // Add framework services.

     services.AddMvc();

     services.AddDbContext<MvcMovieContext>(options =>

             options.UseSqlServer(Configuration.GetConnectionString("MvcMovieContext")));

 }

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 文件获取链接字符串的值:

 "ConnectionStrings": {

   "MvcMovieContext": "Server=(localdb)\\mssqllocaldb;Database=MvcMovieContext-20613a4b-deb5-4145-b6cc-a5fd19afda13;Trusted_Connection=True;MultipleActiveResultSets=true"

 }

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 类,用下面的代码替换掉自动生成的代码:

 using Microsoft.EntityFrameworkCore;

 using Microsoft.Extensions.DependencyInjection;

 using System;

 using System.Linq;

 namespace MvcMovie.Models

 {

     public static class SeedData

     {

         public static void Initialize(IServiceProvider serviceProvider)

         {

             using (var context = new MvcMovieContext(

                 serviceProvider.GetRequiredService<DbContextOptions<MvcMovieContext>>()))

             {

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

             }

         }

     }

 }

C# Code

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

如果数据库中有数据记录,就会直接返回,如果没有就会添加这些初始数据。

 if (context.Movie.Any())

 {

     return;   // DB has been seeded.

 }

C# Code

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

把数据初始化类添加到Startup.cs 文件的Configure  方法的最后一行:

             app.UseStaticFiles();

             app.UseMvc(routes =>

             {

                 routes.MapRoute(

                     name: "default",

                     template: "{controller=Home}/{action=Index}/{id?}");

             });

             SeedData.Initialize(app.ApplicationServices);

         }

     }

 }

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 周一

009.Working with SQL Server LocalDB --【在sql server localdb 上操作数据】的更多相关文章

  1. Comparison of SQL Server Compact, SQLite, SQL Server Express and LocalDB

    Information about LocalDB comes from here and SQL Server 2014 Books Online. LocalDB is the full SQL ...

  2. Azure SQL Database (20) 使用SQL Server 2016 Upgrade Advisor

    <Windows Azure Platform 系列文章目录>  Azure SQL Database (19) Stretch Database 概览      Azure SQL Da ...

  3. SQL SERVER如何通过SQL语句获服务器硬件和系统信息

    在SQL SERVER中如何通过SQL语句获取服务器硬件和系统信息呢?下面介绍一下如何通过SQL语句获取处理器(CPU).内存(Memory).磁盘(Disk)以及操作系统相关信息.如有不足和遗漏,敬 ...

  4. 使用sql语句创建修改SQL Server标识列(即自动增长列)

    一.标识列的定义以及特点SQL Server中的标识列又称标识符列,习惯上又叫自增列.该种列具有以下三种特点:1.列的数据类型为不带小数的数值类型2.在进行插入(Insert)操作时,该列的值是由系统 ...

  5. SQL Server如何在变长列上存储索引

    这篇文章我想谈下SQL Server如何在变长列上存储索引.首先我们创建一个包含变长列的表,在上面定义主键,即在上面定义了聚集索引,然后往里面插入80000条记录: -- Create a new t ...

  6. MS SQL Server2014链接MS SQL Server 2000

    开发与企业应用中,好几个版本SQL Server相互链接.分布式读取与存储,需要实现sp_addlinkedserver.SQL Server 2000, SQL Server 2008, SQL S ...

  7. SQL Server:查看SQL日志文件大小命令:dbcc sqlperf(logspace)

      SQL Server:查看SQL日志文件大小命令:dbcc sqlperf(logspace) DBA 日常管理工作中,很重要一项工作就是监视数据库文件大小,及日志文件大小.如果你管理数据库的有很 ...

  8. SQL Server 2012:SQL Server体系结构——一个查询的生命周期(第1部分)

    为了缩小读取操作所涉及范围,本文首先着眼于简单的SELECT查询,然后引入执行更新操作有关的附加过程.最后你会读到,优化性能时SQLServer使用还原工具的相关术语和流程. 关系和存储引擎 如图所示 ...

  9. SQL Server 2012:SQL Server体系结构——一个查询的生命周期(第2部分)

    计划缓存(Plan Cache) 如果SQL Server已经找到一个好的方式去执行一段代码时,应该把它作为随后的请求重用,因为生成执行计划是耗费时间且资源密集的,这样做是有有意义的. 如果没找到被缓 ...

随机推荐

  1. 【52ABP实战教程】00-- ASP.NET CORE系列介绍

    为什么是.net core? 记得在半年前.NET CORE刚刚出了1.0,当时有朋友推荐我使用的时候,个人觉得还不成熟. 现在.NET Core已经到了2.0,.NET Standard 2.0 添 ...

  2. windbg分析Kernel32.dll导出表

    写在前面的话: 继续上篇,在获得了Kernel32.dll基址的基础上,分析它的导出表结构: 对PE结构不太熟悉的同学,可以参考看雪论坛里的一篇帖子:https://bbs.pediy.com/thr ...

  3. Java课后练习

    1.利用循环输出:************************* public class Shape { public static void main(String[] args) { for ...

  4. python列表基础操作

    Python列表基本操作 记住一句话,叫做顾首不顾尾 首先我们来定义一个列表 name = ["jixuege","dajiba","boduoye& ...

  5. jQuery 事件绑定 和 JavaScript 原生事件绑定

    总结一下:jQuery 事件绑定 和 JavaScript 原生事件绑定 及 区别 jQuery 事件绑定 jQuery 中提供了四种事件监听绑定方式,分别是 bind.live.delegate.o ...

  6. 在一个没有设置宽高的容器中,为什么设置position:absolute后就可以全屏显示了?

    此场景适用于移动端百分比布局,背景全屏显示. 在一个没有设置宽高的容器中设置背景,想要背景全屏显示,设置bcakground-size:100%;后还需设置position:absolut; 原因: ...

  7. 九,微信小程序开发浅谈

    最近在帮朋友做一款微信小程序(后面统称为小程序),有简单的交互,以及分享和支付功能.下面就简单的对小程序开发做一个简单的介绍,希望可以帮助大家!!! 当前的小程序我们是在windows系统里开发的,如 ...

  8. 对于手机APP偷窥个人隐私,你怎么看

    经过进两周的持续发酵,Facebook5000万用户数据泄露事件,已让其处在舆论的风尖浪口.对于手机APP泄漏用户个人隐私问题,再次受到人们的关注.对于这个问题,你会怎么看? 隐私,即不愿公开的个人信 ...

  9. 微信小程序开发•模块化

    微信小程序的MINA框架,其实是许多前端开发技术的组合.这篇文章中,我们来简单地讨论一下模块化. 1.模块化标准 玩前端的同学大部分都知道模块化的几个标准,CommonJs / AMD / CMD.这 ...

  10. 浅谈SSRF漏洞

    SSRF漏洞是如何产生的? SSRF(Server-Side Request Forgery:服务器端请求伪造) 是一种由攻击者构造形成由服务端发起请求的一个安全漏洞.一般情况下,SSRF是要目标网站 ...