asp.net core 使用EF7 Code First 创建数据库,同时使用命令创建数据库
1.首先下载vs2015的Asp.Net Core(RC2)的插件工具(https://www.microsoft.com/net/core#windows)
2.创建一个asp.net Core的项目,这里我创建一个最简单的项目,就是一个console,在这个基础上我准备一步一步搭建一个Asp.Net Core的项目
3.添加相关的依赖(mvc的依赖和EF的依赖)在projecr.json中:
- {
- "dependencies": {
- "Microsoft.NETCore.App": {
- "version": "1.0.0-rc2-3002702",
- "type": "platform"
- },
- "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0-rc2-final",
- "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-rc2-final",
- "Microsoft.AspNetCore.StaticFiles": "1.0.0-rc2-final",
- "Microsoft.AspNetCore.Mvc": "1.0.0-rc2-final",
- "Microsoft.AspNetCore.Razor.Tools": {
- "version": "1.0.0-preview1-final",
- "type": "build"
- },
- "Npgsql.EntityFrameworkCore.PostgreSQL": "1.0.0-rc2-release1",
- "Microsoft.EntityFrameworkCore.Tools": {
- "version": "1.0.0-preview1-final",
- "type": "build"
- },
- "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0-rc2-final",
- "Microsoft.Extensions.Configuration.Json": "1.0.0-rc2-final",
- "Microsoft.Extensions.Logging": "1.0.0-rc2-final",
- "Microsoft.Extensions.Logging.Console": "1.0.0-rc2-final",
- "Microsoft.Extensions.Logging.Debug": "1.0.0-rc2-final"
- },
- "tools": {
- "Microsoft.AspNetCore.Razor.Tools": {
- "version": "1.0.0-preview1-final",
- "imports": "portable-net45+win8+dnxcore50"
- },
- "Microsoft.AspNetCore.Server.IISIntegration.Tools": {
- "version": "1.0.0-preview1-final",
- "imports": "portable-net45+win8+dnxcore50"
- },
- "Microsoft.EntityFrameworkCore.Tools": {
- "version": "1.0.0-preview1-final",
- "imports": [
- "portable-net45+win8+dnxcore50",
- "portable-net45+win8"
- ]
- }
- },
- "frameworks": {
- "netcoreapp1.0": {
- "imports": [
- "dotnet5.6",
- "dnxcore50",
- "portable-net45+win8"
- ]
- }
- },
- "buildOptions": {
- "emitEntryPoint": true,
- "preserveCompilationContext": true
- },
- "runtimeOptions": {
- "gcServer": true
- },
- "publishOptions": {
- "include": [
- "wwwroot",
- "web.config"
- ]
- },
- "scripts": {
- "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
- }
- }
4。在Startup.cs 文件中做如下修改:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.Http;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.Logging;
- namespace SmBlog
- {
- public class Startup
- {
- public Startup(IHostingEnvironment env)
- {
- var builder = new ConfigurationBuilder()
- .SetBasePath(env.ContentRootPath)
- .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
- .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
- if (env.IsDevelopment())
- {
- }
- builder.AddEnvironmentVariables();
- Configuration = builder.Build();
- }
- public IConfigurationRoot Configuration { get; }
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddMvc();
- }
- // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
- public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
- {
- loggerFactory.AddConsole(Configuration.GetSection("Logging"));
- loggerFactory.AddDebug();
- app.UseStaticFiles();
- app.UseMvc(routes =>
- {
- routes.MapRoute(
- name: "default",
- template: "{controller=Home}/{action=Index}/{id?}");
- }
- );
- }
- }
- }
现在并没有添加Ef的服务。
5.新建一个appsettings.json 文件用于项目相关配置,在Startup.cs中的log的配置,以及后来的EF数据库的配置都在这个文件中。
- {
- "ConnectionStrings": {
- "PostgreSql": "User ID=postgres;Password=123456;Host=localhost;Port=5432;Database=smbloh"
- },
- "Logging": {
- "IncludeScopes": false,
- "LogLevel": {
- "Default": "Debug",
- "System": "Information",
- "Microsoft": "Information"
- }
- }
- }
6.依照MVC5中的项目目录结构创建如Controllers 和Views和Models文件如下图所示,新建一个HomeController 和Index Action和Index的视图,用于测试。
7.用过dotnet的方式运行(dotnet 相当于之前的dnx) 看到这个结果说明mvc6项目搭建完成
8.开始Ef的操作。在Models中新建一个实体Article简单的给他三个字段
- public class Article
- {
- public int Id { set; get; }
- public string Title { set; get; }
- public string Description { set; get; }
- }
9.在Models中新建一个SMContext(ef上下文对象)代码如下:
- public class SMContext : DbContext
- {
- public SMContext(DbContextOptions option) : base(option)
- {
- }
- public DbSet<Article> Articles { set; get; }
- protected override void OnModelCreating(ModelBuilder modelBuilder)
- {
- base.OnModelCreating(modelBuilder);
- }
- }
10.修改Startup.cs 文件。增加对Ef的支持:代码如下
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddMvc();
- services.AddDbContext<SMContext>(option => option.UseNpgsql(Configuration.GetConnectionString("PostgreSql")));
- }
11.为了初始化数据库,在此新建一个SampleData类,在项目启动的时候,调用此类,进行数据库的初始化。代码如下:
- namespace SmBlog.Models
- {
- public class SampleData
- {
- public async static Task InitDB(IServiceProvider service)
- {
- var db = service.GetService<SMContext>();
- if (db.Database != null && db.Database.EnsureCreated())
- {
- Article article = new Article
- {
- Title = "test",
- Description = "SMBlog Test"
- };
- db.Articles.Add(article);
- await db.SaveChangesAsync();
- }
- }
- }
- }
这个地方比较灵活,我们初始化创建数据库的时候可以插入一条数据,也可以不插入。我在这个地方插入了一条文章的数据。当然系统中有用户,插入管理员是比较适当的操作的。
12.再次修改Startup文件 调用SampleData 在加载项目的时候创建数据库 并初始化。代码如下:
- public async void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
- {
- loggerFactory.AddConsole(Configuration.GetSection("Logging"));
- loggerFactory.AddDebug();
- app.UseStaticFiles();
- app.UseMvc(routes =>
- {
- routes.MapRoute(
- name: "default",
- template: "{controller=Home}/{action=Index}/{id?}");
- }
- );
- await SampleData.InitDB(app.ApplicationServices);
- }
13.再次启动项目,我的数据已经创建成功,并且插入一条数据。如图:
14.数据库迁移 。当我们增加一个User实体,并且修改了Article的实体,现在要进行数据库的迁移,不是简单的把数据库删除重新建立。要保证原有的数据不变,修改数据库结构。
增加的User实体如下:
- public class User
- {
- public int Id { set; get; }
- public string UserName { set; get; }
- public string Password { set; get; }
- }
修改后的Article实体如下,加了个Label的字段
- public class Article
- {
- public int Id { set; get; }
- public string Title { set; get; }
- public string Description { set; get; }
- public string Label { set; get; }
}
在SMContext文件中,增加User的DbConetxt;
如下代码:
- public DbSet<User> Users { set; get; }
15.在vs的PM命令输入 Add-Migration newBook
成功后会在项目中产生一个Migrations文件夹。里面有个快照文件和一个迁移的文件。在此不扩展了。
在执行命令: Update-Database newBook 发现报错了
问题解决,不用SampleData来初始化数据库,用 Add-Migration init Update-Database init 来初始化数据库。
注:也可以在cmd控制台输入命令来实现code first
首先打开cmd 切换到项目的project.json 文件所在文件。执行如下命令
- dotnet ef migrations add FirstMigration
- dotnet ef database update
asp.net core 使用EF7 Code First 创建数据库,同时使用命令创建数据库的更多相关文章
- 创建基于ASP.NET core 3.1 的RazorPagesMovie项目(一)-创建和使用默认的模板
声明:参考于asp.net core 3.1 官网(以后不再说明) 本教程是系列教程中的第一个教程,介绍生成 ASP.NET Core Razor Pages Web 应用的基础知识. 在本系列结束时 ...
- 学习ASP.NET Core Razor 编程系列十一——把新字段更新到数据库
学习ASP.NET Core Razor 编程系列目录 学习ASP.NET Core Razor 编程系列一 学习ASP.NET Core Razor 编程系列二——添加一个实体 学习ASP.NET ...
- 在ASP.NET Core中如何支持每个租户数据存储策略的数据库
在ASP.NET Core中如何支持每个租户数据存储策略的数据库 不定时更新翻译系列,此系列更新毫无时间规律,文笔菜翻译菜求各位看官老爷们轻喷,如觉得我翻译有问题请挪步原博客地址 本博文翻译自: ht ...
- ASP.NET Core EFCore 之Code First
1.在.NET Core项目中使用Nuget引用包 Sql Server 请安装 Microsoft.EntityFrameworkCore.SqlServer 2.添加实体类 [Table(&quo ...
- asp.net core for vs code
1,命令 2,模板 3,更换启动浏览器 4,vscode使用nuget 5,使用ef migration 6,配置.net core的工作目录 7,使用dotnet ef migrations命令 8 ...
- ASP.NET Core 中文文档 第二章 指南(2)用 Visual Studio 和 ASP.NET Core MVC 创建首个 Web API
原文:Building Your First Web API with ASP.NET Core MVC and Visual Studio 作者:Mike Wasson 和 Rick Anderso ...
- Docker 为 ASP.NET Core WebApi 应用程序生成 Docker 映像,创建容器并运行
1.使用VS2017新建ASP.NET Core WebApi项目 选择API启用Docker支持 2.为 ASP.NET Core WebApi 应用程序生成 Docker 映像,并创建容器运行 生 ...
- kubernetes高级之创建只读文件系统以及只读asp.net core容器
系列目录 使用docker创建只读文件系统 容器化部署对应用的运维带来了极大的方便,同时也带来一些新的安全问题需要考虑.比如黑客入侵到容器内,对容器内的系统级别或者应用级别文件进行修改,会造成难以估量 ...
- Asp.Net Core 项目实战之权限管理系统(3) 通过EntityFramework Core使用PostgreSQL
0 Asp.Net Core 项目实战之权限管理系统(0) 无中生有 1 Asp.Net Core 项目实战之权限管理系统(1) 使用AdminLTE搭建前端 2 Asp.Net Core 项目实战之 ...
随机推荐
- PXC(Percona XtraDB Cluster)集群的安装与配置
Percona XtraDB Cluster是针对MySQL用户的高可用性和扩展性解决方案,基于Percona Server .其包括了Write Set REPlication补丁,使用Galera ...
- Java基础知识笔记(三:文件与数据流)
一.输入流与输出流 输入流将数据从文件.标准输入或其他外部输入设备中加载到内存.输出流的作用则刚好相反,即将在内存中的数据保存到文件中,或传输给输出设备.输入流在Java语言中对应于抽象类java.i ...
- 敏捷BI比传统BI功能强大是否属实?
关于大数据的资讯铺天盖地而来,让人眼花缭乱.虽然资讯很精彩,我们也看到了大数据背后的价值,很多企业选择了商业智能BI产品.商业智能在使用上可分为敏捷BI与传统BI,从名字来看敏捷BI要比传统BI显得利 ...
- QuickHit项目(输出字符串游戏)
public class leve { private int leveNo; private int strLength; private int strTimes; private int tim ...
- 第19章 集合框架(3)-Map接口
第19章 集合框架(3)-Map接口 1.Map接口概述 Map是一种映射关系,那么什么是映射关系呢? 映射的数学解释 设A,B是两个非空集合,如果存在一个法则,使得对A中的每一个元素a,按法则f,在 ...
- MySQL的基本知识 -- 命令
1.数据库和表 SHOW DATABASES; 返回可用数据库的一个列表 SHOW TABLES; 返回一个数据库内的表的列表 SHOW COLUMNS FROM tableName; 返回数据表的表 ...
- MVC5 + EF6 + Bootstrap3 (16) 客户端验证
Slark.NET-博客园 http://www.cnblogs.com/slark/p/mvc5-ef6-bs3-get-started-client-side-validation.html 系列 ...
- Ubuntu 安裝 嘸蝦米 輸入法
O S : 14.04.1-Ubuntu 加入fcitx開發團隊的repository: sudo add-apt-repository ppa:fcitx-team/nightly sudo apt ...
- Android只能动态注册的广播Action
只能动态注册的广播(部分): android.intent.action.SCREEN_ON android.intent.action.SCREEN_OFF android.intent.actio ...
- sql 关于查询时 出现的 从数据类型 varchar 转换为 numeric 时出错 的解决方法。
出现这种问题 一般是查询时出现了 varchar 转 numeric 时出了错 或varchar字段运算造成的 解决方法: 让不能转的数不转换就可以了 sql的函数有个isNumeric(参数) 用 ...