您好,登錄后才能下訂單哦!
這篇文章主要介紹了Entity Framework Core如何使用控制臺程序生成數(shù)據(jù)庫表,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
我們使用Code First的方式來生成數(shù)據(jù)庫表,我們先講解如何在控制臺項(xiàng)目中生成數(shù)據(jù)庫表。
在前面的文章中,我們是直接在控制臺項(xiàng)目中安裝的Mircosoft.EntityFrameworkCore,在真實(shí)的項(xiàng)目中,我們很少這樣使用,都是采用分層的結(jié)構(gòu),將EF Core有關(guān)的操作放在一個單獨(dú)的類庫項(xiàng)目里,下面的例子中我們就以這種分層的結(jié)構(gòu)來進(jìn)行講解。項(xiàng)目結(jié)構(gòu)如下圖所示:
項(xiàng)目結(jié)構(gòu):
EFCoreTest.Con:控制臺項(xiàng)目,用來運(yùn)行程序,在項(xiàng)目中會引用EFCoreTest.Data。
EFCoreTest.Data:類庫項(xiàng)目,基于.Net Standard。存放的是與EF Core相關(guān)的內(nèi)容。
EFCoreTest.Model:類庫項(xiàng)目,基于.Net Standard。存放項(xiàng)目中使用到的實(shí)體類。
我們首先在EFCoreTest.Model類庫項(xiàng)目里添加Student實(shí)體:
namespace EFCoreTest.Model { public class Student { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } public int Gender { get; set; } } }
我們在EFCoreTest.Data類庫里面添加Mircosoft.EntityFrameworkCore包:
我們使用SqlServer數(shù)據(jù)庫,所以我們還要安裝Microsoft.EntityFrameworkCore.sqlServer包:
安裝完成以后我們添加EFCoreTest.Model的引用,然后添加數(shù)據(jù)上下文類,該類繼承自DbContext:
using EFCoreTest.Model; using Microsoft.EntityFrameworkCore; namespace EFCoreTest.Data { /// <summary> /// 數(shù)據(jù)上下文類,繼承自DbContext /// </summary> public class EFCoreDbContext:DbContext { /// <summary> /// 重寫OnConfiguring方法 /// </summary> /// <param name="optionsBuilder"></param> protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { // 使用SqlServer數(shù)據(jù)庫,傳遞連接字符串 optionsBuilder.UseSqlServer("Data Source=.;Initial Catalog=EFTestDb;User ID=sa;Password=123456;"); base.OnConfiguring(optionsBuilder); } /// <summary> /// 重寫OnModelCreating,主要做一些配置 /// 例如設(shè)置生成的表名、主鍵、字符長度 /// </summary> /// <param name="modelBuilder"></param> protected override void OnModelCreating(ModelBuilder modelBuilder) { // 設(shè)置生成的表名 modelBuilder.Entity<Student>().ToTable("T_Student"); // 設(shè)置主鍵,可以不設(shè)置,會默認(rèn)把Id字段當(dāng)成主鍵 modelBuilder.Entity<Student>().HasKey(p => p.Id); // 設(shè)置Name字段的最大長度 modelBuilder.Entity<Student>().Property("Name").HasMaxLength(32); base.OnModelCreating(modelBuilder); } // DbSet屬性 public DbSet<Student> Students { get; set; } } }
這些工作做好以后,我們就可以用來生成數(shù)據(jù)庫表了。
我們下面以三種方式來生成數(shù)據(jù)庫表。首先在控制臺項(xiàng)目中添加EFCoreTest.Data的引用。
我們可以使用代碼來生成數(shù)據(jù)庫,這樣在程序啟動的時候調(diào)用生成數(shù)據(jù)庫的代碼就能自動生成數(shù)據(jù)庫了。代碼如下:
using EFCoreTest.Data; using System; namespace EFCoreTest.Con { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); EFCoreDbContext dbContext = new EFCoreDbContext(); bool tfTrue = dbContext.Database.EnsureCreated(); if (tfTrue) { Console.WriteLine("數(shù)據(jù)庫創(chuàng)建成功!"); } else { Console.WriteLine("數(shù)據(jù)庫創(chuàng)建失敗!"); } Console.ReadKey(); } } }
運(yùn)行程序:
輸出結(jié)果提示我們創(chuàng)建成功了,在去數(shù)據(jù)庫里面看看:
我們看到數(shù)據(jù)庫和表都已經(jīng)生成了,而且表里面的字段屬性是按照我們在代碼里面的設(shè)置生成的。
注意:如果這時候在程序啟動的時候在去生成數(shù)據(jù)庫就會報(bào)錯:
除了使用代碼的方式生成,我們還可以使用數(shù)據(jù)遷移命令來生成數(shù)據(jù)庫表,分為下面的三個步驟。
要使用數(shù)據(jù)遷移命令,首先需要安裝Microsoft.EntityFrameworkCore.Tools包:
首先在數(shù)據(jù)上下文類的OnModelCreating()方法里面添加一些種子數(shù)據(jù),這樣生成數(shù)據(jù)庫以后,表里面就有一些基礎(chǔ)數(shù)據(jù):
using EFCoreTest.Model; using Microsoft.EntityFrameworkCore; namespace EFCoreTest.Data { /// <summary> /// 數(shù)據(jù)上下文類,繼承自DbContext /// </summary> public class EFCoreDbContext:DbContext { /// <summary> /// 重寫OnConfiguring方法 /// </summary> /// <param name="optionsBuilder"></param> protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { // 使用SqlServer數(shù)據(jù)庫,傳遞連接字符串 optionsBuilder.UseSqlServer("Data Source=.;Initial Catalog=EFTestDb;User ID=sa;Password=123456;"); base.OnConfiguring(optionsBuilder); } /// <summary> /// 重寫OnModelCreating,主要做一些配置 /// 例如設(shè)置生成的表名、主鍵、字符長度 /// </summary> /// <param name="modelBuilder"></param> protected override void OnModelCreating(ModelBuilder modelBuilder) { // 設(shè)置生成的表名 modelBuilder.Entity<Student>().ToTable("T_Student"); // 設(shè)置主鍵,可以不設(shè)置,會默認(rèn)把Id字段當(dāng)成主鍵 modelBuilder.Entity<Student>().HasKey(p => p.Id); // 設(shè)置Name字段的最大長度 modelBuilder.Entity<Student>().Property("Name").HasMaxLength(32); base.OnModelCreating(modelBuilder); // 添加種子數(shù)據(jù) modelBuilder.Entity<Student>().HasData( new Student() { Id = 1, Name = "Tom", Age = 24, Gender = 1 }, new Student() { Id = 2, Name = "Jack", Age = 23, Gender = 2 }, new Student() { Id = 3, Name = "Kevin", Age = 26, Gender = 2 } ); } // DbSet屬性 public DbSet<Student> Students { get; set; } } }
然后使用下面的命令來添加遷移:
Add-Migration Initial
Add-Migration:是遷移命令。
Initial:可以理解成是給這次遷移起的一個別名,這個名稱可以任意起,只要保證每次遷移的時候不重名即可。
如下圖所示:
執(zhí)行這條命令:
我們看到執(zhí)行報(bào)錯了,報(bào)錯信息提示我們程序的啟動項(xiàng)里面也要安裝Mircosoft.EntityFrameworkCore.Tools包,我們在控制臺程序里面安裝這個包,然后在執(zhí)行遷移命令:
可以看到,這次執(zhí)行成功了。成功以后會生成一個Migrations文件夾,這個文件夾下面有兩個類文件:
20200223132908_Init.cs文件是根據(jù)這次遷移生成的文件,里面記錄著這次遷移發(fā)生的改變:
using Microsoft.EntityFrameworkCore.Migrations; namespace EFCoreTest.Data.Migrations { public partial class Init : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "T_Student", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Name = table.Column<string>(maxLength: 32, nullable: true), Age = table.Column<int>(nullable: false), Gender = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_T_Student", x => x.Id); }); migrationBuilder.InsertData( table: "T_Student", columns: new[] { "Id", "Age", "Gender", "Name" }, values: new object[] { 1, 24, 1, "Tom" }); migrationBuilder.InsertData( table: "T_Student", columns: new[] { "Id", "Age", "Gender", "Name" }, values: new object[] { 2, 23, 2, "Jack" }); migrationBuilder.InsertData( table: "T_Student", columns: new[] { "Id", "Age", "Gender", "Name" }, values: new object[] { 3, 26, 2, "Kevin" }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "T_Student"); } } }
里面有下面的兩個方法:
Up:該方法是要應(yīng)用到數(shù)據(jù)庫的配置。
Down:該方法相當(dāng)于是做回滾操作,執(zhí)行這個方法,可以恢復(fù)到上一個狀態(tài)。
每進(jìn)行一次遷移就會生成一個這樣的文件。
EFCoreDbContextModelSnapshot.cs是根據(jù)在OnModelCreating()方法中的配置生成的文件:
// <auto-generated /> using EFCoreTest.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace EFCoreTest.Data.Migrations { [DbContext(typeof(EFCoreDbContext))] partial class EFCoreDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.1.2") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("EFCoreTest.Model.Student", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("Age") .HasColumnType("int"); b.Property<int>("Gender") .HasColumnType("int"); b.Property<string>("Name") .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.HasKey("Id"); b.ToTable("T_Student"); b.HasData( new { Id = 1, Age = 24, Gender = 1, Name = "Tom" }, new { Id = 2, Age = 23, Gender = 2, Name = "Jack" }, new { Id = 3, Age = 26, Gender = 2, Name = "Kevin" }); }); #pragma warning restore 612, 618 } } }
執(zhí)行完上面的步驟,我們執(zhí)行更新數(shù)據(jù)庫的命令:
Update-Database
如下圖所示:
執(zhí)行成功,查看數(shù)據(jù)庫數(shù)據(jù):
T_Student表已經(jīng)生成了,而且表里面也有添加的種子數(shù)據(jù),到此遷移就完成了。
除了上面的兩種方式,還可以使用命令行進(jìn)行遷移,這種方式主要在Web項(xiàng)目里面比較常用。
使用下面的命令安裝:
dotnet tool install --global dotnet-ef
如下圖所示:
安裝完成以后我們在執(zhí)行命令:
因?yàn)槲冶緳C(jī)的.NET SDK的版本是3.1.1,剛才安裝的dotent-ef的版本是3.1.2,版本不兼容,我們下載最新的.NET SDK,然后安裝。
感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“Entity Framework Core如何使用控制臺程序生成數(shù)據(jù)庫表”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識等著你來學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。