Asp.net core 通過Models 生成數據庫的方法


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM