.Net開源框架ABP初探(二)— 使用Code First方式建立資料表
- 開啟.Core專案,新建新建一個專案資料夾(Clothes);
為了演示表關聯及外來鍵的使用,建立兩個類: - 建立類ClothesCategoty.cs
using Abp.Domain.Entities; namespace myTest.Clothes { public class ClothesCategory:Entity { public virtual string Name { get; set; } } }
using Abp.Domain.Entities引用Abp.Domain.Entities,abp中所有的類都繼承自Abp.Domain.Entities.Entity,整合後會自動建立表主鍵欄位Id。
- 建立類Clothes.cs
using System; using System.ComponentModel.DataAnnotations.Schema; using Abp.Domain.Entities; namespace myTest.Clothes { [Table("Clothes")] public class Clothes:Entity { public virtual DateTime CreationTime { get; set; } public virtual string PictureUrl { get; set; } [ForeignKey("ClothesCategoryId")] public virtual ClothesCategory ClothesCategory { get; set; } } }
[Table(“xxx”)]指定表名,不指定預設使用類名;[ForeignKey(“xxx”)]指定關聯表外來鍵的名稱。
2.新增類到DbContext
開啟.EntityFrameworkCore專案,找到xxxDbContext類,在類中加入新模型的相關程式碼:
public virtual DbSet<Clothes.Clothes> Clothes { get; set; } public virtual DbSet<Clothes.ClothesCategory> ClothesCategory { get; set; }
如下圖:

3.執行命令
開啟NuGet程式包管理控制檯,選擇預設專案為.EntityFrameworkCore專案。
-
執行Add-Migration xxxx,其中xxxx可自主命名;
執行完成後會在專案的Migrations資料夾下自動生成兩個檔案,如下圖:
-
執行“Update-Database”
至此,資料庫表建立完成。