其实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,只能自行更新了。

Asp.net core 通过Models 生成数据库的方法的更多相关文章

  1. ASP.NET Core 设置和初始化数据库 - ASP.NET Core 基础教程 - 简单教程,简单编程

    原文:ASP.NET Core 设置和初始化数据库 - ASP.NET Core 基础教程 - 简单教程,简单编程 ASP.NET Core 设置和初始化数据库 上一章节中我们已经设置和配置好了 EF ...

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

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

  3. asp.net core web api 生成 swagger 文档

    asp.net core web api 生成 swagger 文档 Intro 在前后端分离的开发模式下,文档就显得比较重要,哪个接口要传哪些参数,如果一两个接口还好,口头上直接沟通好就可以了,如果 ...

  4. 【无私分享:ASP.NET CORE 项目实战(第十三章)】Asp.net Core 使用MyCat分布式数据库,实现读写分离

    目录索引 [无私分享:ASP.NET CORE 项目实战]目录索引 简介 MyCat2.0版本很快就发布了,关于MyCat的动态和一些问题,大家可以加一下MyCat的官方QQ群:106088787.我 ...

  5. .NET跨平台:在Linux上基于ASP.NET 5用EF7生成数据库

    Linux用的是Ubuntu,dnx版本是1.0.0-beta6-12120,EF版本是7.0.0-beta5. 以下是用Entity Framework 7生成SQL Server数据库的操作步骤. ...

  6. asp.net core 使用 swagger 生成接口文档

    参考地址:http://www.cnblogs.com/daxnet/p/6181366.html http://www.jianshu.com/p/fa5a9b76f3ed 微软参考文档:https ...

  7. 基于ASP.NET Core Data Protection生成验证token

    ASP.NET Core Data Protection 不仅提供了非对称加密能力,而且提供了灵活的秘钥存储方式以及一致的加解密接口(Protect与Unprotect).Session中用到了它,C ...

  8. linux 环境下部署 Asp.Net Core 项目 访问 oralce 数据库

    1.ASP.NET Core 是一个跨平台的高性能开源框架,可以部署到Linux上,那项目部署在Linux上有哪些好处呢? 1.linux硬件需求小,大部分版本免费,成本低. 2.linux的用户管理 ...

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

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

随机推荐

  1. RMQ算法模板

    分别写了下标从0和1开始的两种 #include<stdio.h> #include<string.h> #include<algorithm> #include& ...

  2. 如何在Jenkins CI 里调试

    背景 厂内的CI系统把 Jenkins 和Github 连接了起来,这样Dev 只要通过github pr 就能够了解到测试job 运行的情况.有的时候,Dev会找到QA问,如何在Jenkins CI ...

  3. [课程设计]Scrum 1.7 多鱼点餐系统开发进度

    [课程设计]Scrum 1.7 多鱼点餐系统开发进度(点餐菜式内容添加及美化) 1.团队名称:重案组 2.团队目标:长期经营,积累客户充分准备,伺机而行 3.团队口号:矢志不渝,追求完美 4.团队选题 ...

  4. IntelliJ IDEA 的 20 个代码自动完成的特性

    http://www.oschina.net/question/12_70799 在这篇文章中,我想向您展示 IntelliJ IDEA 中最棒的 20 个代码自动完成的特性,可让 Java 编码变得 ...

  5. 井间数据polarization analysis 相关概念

    1. 垂直分量上记录到的数据,无法记录SH波?这个有待考证,先记录于此~ 两点需要注意:1.层状介质中,P波和深度方向(Z轴)组成入射面;2.SH的定义为垂直于入射面的S波分量. 2.VSP的观测方式 ...

  6. (转) 变分自编码器(Variational Autoencoder, VAE)通俗教程

    变分自编码器(Variational Autoencoder, VAE)通俗教程 转载自: http://www.dengfanxin.cn/?p=334&sukey=72885186ae5c ...

  7. hosts 文件妙用

        127.0.0.1  localhost  www.baidu.com  www.126.com  www.xiaoxiao.com 1: 如果在hosts文件中加入这句话,则localhos ...

  8. sqlserver和Oracle内部的错误数据修复(DBCC、DBMS_REPAIR)

    数据库长时间运行后,因断电.操作系统.物理存储等的原因可能会造成数据库内部的逻辑或物理错误,我们可以使用一般的方式尝试修复. 对于sqlserver 我们可以使用DBCC命令: -- sqlserve ...

  9. KO中对象数组排序时,两个属性的优先顺序不一致时的排序实现

    function FromSort(left, right, asc) {    if (left.属性1 != "") {        if (right.属性1 != &qu ...

  10. [转]libevent简介和使用

    libevent是一个基于事件触发的网络库,memcached底层也是使用libevent库. 总体来说,libevent有下面一些特点和优势:* 事件驱动,高性能:* 轻量级,专注于网络: * 跨平 ...