其实Getting Started当中有着详细的说明,https://docs.efproject.net/en/latest/platforms/aspnetcore/new-db.html。但是有网友问道,就说一下好了。

  1. 新建项目,Asp.net core,选择不适用身份验证。
  2. 添加项目引用。这里还是使用postgreSql。

    在Nuget 控制台中输入命令:

    Install-Package Npgsql.EntityFrameworkCore.PostgreSQL

    Install-Package Microsoft.EntityFrameworkCore.Tools –Pre

    添加这两个依赖

    然后手动在Tools 节点中加上 "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",

    这里发现Tools –Pre就可以正常使用nuget安装,昨天直接获取版本安装失败,看来还是nuget同步问题。

  3. 创建Model类 Blogs,Post和DBContext

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Threading.Tasks;

    namespace PostgreSqlDemo2.Models

    {

    public class Blog

    {

    public int BlogId { get; set; }

    public string Url { get; set; }

    public List<Post> Posts { get; set; }

    }

    }

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Threading.Tasks;

    namespace PostgreSqlDemo2.Models

    {

    public class Post

    {

    public int PostId { get; set; }

    public string Title { get; set; }

    public string Content { get; set; }

    public int BlogId { get; set; }

    public Blog Blog { get; set; }

    }

    }

    using Microsoft.EntityFrameworkCore;

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Threading.Tasks;

    namespace PostgreSqlDemo2.Models

    {

    public class BloggingContext : DbContext

    {

    public BloggingContext(DbContextOptions<BloggingContext> options)

    : base(options)

    { }

    public DbSet<Blog> Blogs { get; set; }

    public DbSet<Post> Posts { get; set; }

    }

    }

  4. 在Startup.cs类中注册DBContext

public void ConfigureServices(IServiceCollection services)

{

// Add framework services.

services.AddApplicationInsightsTelemetry(Configuration);

services.AddDbContext<BloggingContext>(options =>

options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));

services.AddMvc();

}

  1. Appsetting.json中增加连接字符串

    "ConnectionStrings": {

    "DefaultConnection": "User ID=test;Password=test;Host=192.168.1.6;Database=testdb;Pooling=true;"

    },

  2. 创建Migration类

    这里要说一下,Migration是ef框架设计的工具,能够用来生成一些框架类。在vs2015中,可以在Nuget控制台中使用Add-Migration,linux或者cmd中,可以使用dotnet ef migration命令,具体请自行学习。

    言归正传,我们开始生成类,在Nuget控制台中输入命令:

    Add-Migration MyFirstMigration

    等待结束,笔者这里会报一个"无法识别的转义序列"的错误,但是不影响使用,笔者已经在apsnet上报了issue。

    然后我们会看到,项目结构中增加了一个文件夹及几个文件如下:

    查看代码:

    using System;

    using System.Collections.Generic;

    using Microsoft.EntityFrameworkCore.Migrations;

    namespace PostgreSqlDemo2.Migrations

    {

    public partial class MyFirstMigration : Migration

    {

    protected override void Up(MigrationBuilder migrationBuilder)

    {

    migrationBuilder.CreateTable(

    name: "Blogs",

    columns: table => new

    {

    BlogId = table.Column<int>(nullable: false)

    .Annotation("Npgsql:ValueGeneratedOnAdd", true),

    Url = table.Column<string>(nullable: true)

    },

    constraints: table =>

    {

    table.PrimaryKey("PK_Blogs", x => x.BlogId);

    });

    migrationBuilder.CreateTable(

    name: "Posts",

    columns: table => new

    {

    PostId = table.Column<int>(nullable: false)

    .Annotation("Npgsql:ValueGeneratedOnAdd", true),

    BlogId = table.Column<int>(nullable: false),

    Content = table.Column<string>(nullable: true),

    Title = table.Column<string>(nullable: true)

    },

    constraints: table =>

    {

    table.PrimaryKey("PK_Posts", x => x.PostId);

    table.ForeignKey(

    name: "FK_Posts_Blogs_BlogId",

    column: x => x.BlogId,

    principalTable: "Blogs",

    principalColumn: "BlogId",

    onDelete: ReferentialAction.Cascade);

    });

    migrationBuilder.CreateIndex(

    name: "IX_Posts_BlogId",

    table: "Posts",

    column: "BlogId");

    }

    protected override void Down(MigrationBuilder migrationBuilder)

    {

    migrationBuilder.DropTable(

    name: "Posts");

    migrationBuilder.DropTable(

    name: "Blogs");

    }

    }

    }

    Design.cs

    using System;

    using Microsoft.EntityFrameworkCore;

    using Microsoft.EntityFrameworkCore.Infrastructure;

    using Microsoft.EntityFrameworkCore.Metadata;

    using Microsoft.EntityFrameworkCore.Migrations;

    using PostgreSqlDemo2.Models;

    namespace PostgreSqlDemo2.Migrations

    {

    [DbContext(typeof(BloggingContext))]

    [Migration("20160713011245_MyFirstMigration")]

    partial class MyFirstMigration

    {

    protected override void BuildTargetModel(ModelBuilder modelBuilder)

    {

    modelBuilder

    .HasAnnotation("ProductVersion", "1.0.0-rtm-21431");

    modelBuilder.Entity("PostgreSqlDemo2.Models.Blog", b =>

    {

    b.Property<int>("BlogId")

    .ValueGeneratedOnAdd();

    b.Property<string>("Url");

    b.HasKey("BlogId");

    b.ToTable("Blogs");

    });

    modelBuilder.Entity("PostgreSqlDemo2.Models.Post", b =>

    {

    b.Property<int>("PostId")

    .ValueGeneratedOnAdd();

    b.Property<int>("BlogId");

    b.Property<string>("Content");

    b.Property<string>("Title");

    b.HasKey("PostId");

    b.HasIndex("BlogId");

    b.ToTable("Posts");

    });

    modelBuilder.Entity("PostgreSqlDemo2.Models.Post", b =>

    {

    b.HasOne("PostgreSqlDemo2.Models.Blog", "Blog")

    .WithMany("Posts")

    .HasForeignKey("BlogId")

    .OnDelete(DeleteBehavior.Cascade);

    });

    }

    }

    }

    using System;

    using Microsoft.EntityFrameworkCore;

    using Microsoft.EntityFrameworkCore.Infrastructure;

    using Microsoft.EntityFrameworkCore.Metadata;

    using Microsoft.EntityFrameworkCore.Migrations;

    using PostgreSqlDemo2.Models;

    namespace PostgreSqlDemo2.Migrations

    {

    [DbContext(typeof(BloggingContext))]

    partial class BloggingContextModelSnapshot : ModelSnapshot

    {

    protected override void BuildModel(ModelBuilder modelBuilder)

    {

    modelBuilder

    .HasAnnotation("ProductVersion", "1.0.0-rtm-21431");

    modelBuilder.Entity("PostgreSqlDemo2.Models.Blog", b =>

    {

    b.Property<int>("BlogId")

    .ValueGeneratedOnAdd();

    b.Property<string>("Url");

    b.HasKey("BlogId");

    b.ToTable("Blogs");

    });

    modelBuilder.Entity("PostgreSqlDemo2.Models.Post", b =>

    {

    b.Property<int>("PostId")

    .ValueGeneratedOnAdd();

    b.Property<int>("BlogId");

    b.Property<string>("Content");

    b.Property<string>("Title");

    b.HasKey("PostId");

    b.HasIndex("BlogId");

    b.ToTable("Posts");

    });

    modelBuilder.Entity("PostgreSqlDemo2.Models.Post", b =>

    {

    b.HasOne("PostgreSqlDemo2.Models.Blog", "Blog")

    .WithMany("Posts")

    .HasForeignKey("BlogId")

    .OnDelete(DeleteBehavior.Cascade);

    });

    }

    }

    }

    上面代码都是自动生成的,生成依据就是你的Models中的实体类文件。

  3. 创建数据库

    虽然上面生成了数据库架构的代码,但是还没有更新到数据库中去。需要执行:

    Update-Database

    如果显示Done.

    则表示更新数据库成功。可以看看数据库中已经自动根据model实体创建了对应的数据表。

  4. 剩下的工作就和前文一样了,不在细说。

总结:

记住几个命令 "Add-Migration MyFirstMigration","Update-Database"。注意执行时要保证代码能够正常编译,并且已经完成数据库的配置。如果数据库结构改了,可以修改Models下对应的实体类,然后删除Migration文件夹下的文件,然后从新执行这两个命令。笔者这里使用PostgreSQL的时候,报错了,提示Blogs表已存在,应该是issue,只能自行更新了。

转载于:https://www.cnblogs.com/lanwilliam/p/5666143.html

Asp.net core 通过Models 生成数据库的方法相关推荐

  1. Asp.net Core 使用MyCat分布式数据库,实现读写分离

    简介 MyCat2.0版本很快就发布了,关于MyCat的动态和一些问题,大家可以加一下MyCat的官方QQ群:106088787.我们今天主要介绍一下,在我们的Asp.net Core中如何使用Myc ...

  2. ASP.NET Core - Razor页面之Handlers处理方法

    简介 在前一篇文章中,我们讨论了Razor页面.今天我们来谈谈处理方法(Handlers). 我们知道可以将代码和模型放在 .cshtml 文件里面或与 .cshtml 匹配的 .cshtml.cs ...

  3. .NET5.0和SDK 5.0.100以及ASP.NET Core Runtime 5.0.0下载方法

    .net framework 5是一款非常实用的语言开发软件,这款软件的作用就是那个轻松的保障你的电脑软件简单运行正常,而这次带来的是.net framework 5版本,增加了非常多的功能和特色,一 ...

  4. Django在根据models生成数据库表时报 __init__() missing 1 required positional argument 'on_d...

    代码: from django.db import modelsclass Blog(models.Model):name = models.CharField(max_length=100)tagl ...

  5. asp.net core 2.1 Mysql 数据库迁移,遇坑记录

    首先来一段错误 immodeMacBook-Pro:tz.efcontext immo$ dotnet ef database update Unable to create an object of ...

  6. Django在根据models生成数据库表时报 missing 1 required positional argument on_delete(亲测)

    code: 1 #encoding=utf-82 from django.db import models3 # Create your models here.4 class BookInfo(mo ...

  7. Django在根据models生成数据库表时报 __init__() missing 1 required positional argument: 'on_delete'

    code: 1 #encoding=utf-82 from django.db import models3 # Create your models here.4 class BookInfo(mo ...

  8. Django在根据models生成数据库表时报 __init__() missing 1 required positional argument: 'on_delete'...

    在django2.0后,定义外键和一对一关系的时候需要加on_delete选项,此参数为了避免两个表里的数据不一致问题,不然会报错: TypeError: __init__() missing 1 r ...

  9. ASP实现导入Excel数据到数据库的方法

    以下代码为转载,未经验证,仅供参考: <% Response.CodePage=65001%> <% Response.Charset="UTF-8" %> ...

  10. ASP.NET MVC应用迁移到ASP.NET Core及其异同简介

    ASP.NET Core是微软新推出支持跨平台.高性能.开源的开发框架,相比起原有的ASP.NET来说,ASP.NET Core更适合开发现代应用程序,如跨平台.Dorker的支持.集成现代前端开发框 ...

最新文章

  1. matplotlib安装错误依赖问题解决
  2. 【loj6342】跳一跳 期望dp
  3. Java的知识点21——String类、StringBuffer和StringBuilder、不可变和可变字符序列使用陷阱
  4. 持续集成之 Jenkins 的安装与配置(一)
  5. 解决:缺少aclocal、autoconf、automake
  6. 前端经典面试题 不经典不要star!
  7. linux概述、基本命令
  8. Hadoop 实践(一) 环境搭建
  9. Spring 创建对象的方式
  10. GitHub Trending 长期被国人“霸榜”,国外开发者 SAY NO
  11. 推荐21个顶级的Vue UI库!
  12. idea里面的注释模板
  13. 数据分析的发展及数据分析师的技能浅谈
  14. php ubb类,一个用PHP实现的UBB类!-PHP教程,PHP应用
  15. Recylerview刷新图片闪烁
  16. Windows系统文件类型大全
  17. css中好看常用的中文字体
  18. “沙箱机制”是什么?
  19. 留数的相关概念及定理
  20. Spring和SpringBoot简介

热门文章

  1. 以太坊 Solidity 函数返回(returns)多个值 和 接收方式
  2. ElasticSearch 查询最多10000条数据
  3. springmvc中关于post请求会出现乱码的整理
  4. web 前端签名插件_10款前端开发神器,助你成前端高手?
  5. PTA甲级15进制转换
  6. Elasticsearc 6.x以后不再支持mapping下多个type
  7. windows 下 LITE IDE go lang 安装配置使用
  8. wamp怎么安装mysql服务器_使用WAMPServer套件可安装Apache服务器和MySQL服务器
  9. 阶段5 3.微服务项目【学成在线】_day02 CMS前端开发_06-vuejs研究-vuejs基础-v-on指令...
  10. java中参数 ...的用法和意思