1. 程式人生 > 實用技巧 >精簡版Abp開發教程 - 第二章: 建立Book實體及資料遷移

精簡版Abp開發教程 - 第二章: 建立Book實體及資料遷移

我們基於官方教程並結合下列教程,開始建立Book之旅。

建立BookType列舉

Acme.BookStore.Domain.Shared中新增BookType.cs

namespace Acme.BookStore.Domain.Shared.Enums
{
    public enum BookType
    {
        Undefined,
        Adventure,
        Biography,
        Dystopia,
        Fantastic,
        Horror,
        Science,
        ScienceFiction,
        Poetry
    }
}

建立Book實體

Acme.BookStore.Domain中新增Book.cs

namespace Acme.BookStore.Domain.Entities
{
    public class Book : AuditedAggregateRoot<Guid>
    {
        public string Name { get; set; }

        public BookType Type { get; set; }

        public DateTime PublishDate { get; set; }

        public float Price { get; set; }
    }
}

建立DbContext

Acme.BookStore.EntityFrameworkCore中新增BookStoreDbContext.cs

namespace Acme.BookStore.EntityFrameworkCore
{
    [ConnectionStringName("Default")]
    public class BookStoreDbContext : AbpDbContext<BookStoreDbContext>
    {
        public DbSet<Book> Books { get; set; }

        public BookStoreDbContext(DbContextOptions<BookStoreDbContext> options) : base(options)
        {
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            //自動載入資料庫對映配置
            modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
        }
    }
}

這個寫法與官方教程不同,官方是BookStoreDbContextModelCreatingExtensions進行資料庫對映配置

建立Book實體對映

Acme.BookStore.EntityFrameworkCore中新增BookMap.cs

namespace Acme.BookStore.EntityFrameworkCore.Mappings
{
    public class BookMap : IEntityTypeConfiguration<Book>
    {
        public void Configure(EntityTypeBuilder<Book> builder)
        {
            builder.ToTable(nameof(Book));
            builder.ConfigureByConvention();

            builder.Property(x => x.Name).IsRequired().HasMaxLength(128);
        }
    }
}

建立Migrations DbContext Factory類

Acme.BookStore.EntityFrameworkCore.DbMigrations中新增BookStoreMigrationsDbContextFactory.cs

namespace Acme.BookStore.EntityFrameworkCore.DbMigrations
{
    public class BookStoreMigrationsDbContextFactory : IDesignTimeDbContextFactory<BookStoreDbContext>
    {
        public BookStoreDbContext CreateDbContext(string[] args)
        {
            var configuration = BuildConfiguration();

            var builder = new DbContextOptionsBuilder<BookStoreDbContext>()
                .UseSqlServer(
                    configuration.GetConnectionString("Default"),
                    optionsBuilder => optionsBuilder.MigrationsAssembly(Assembly.GetExecutingAssembly().FullName));
            return new BookStoreDbContext(builder.Options);
        }
        
        private static IConfigurationRoot BuildConfiguration()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false);
            return builder.Build();
        }
    }
}

新增appsettings.json

Acme.BookStore.EntityFrameworkCore.DbMigrations中新增appsettings.json

{
    "ConnectionStrings": {
        "Default": "Server=(LocalDb)\\MSSQLLocalDB;Database=Acme.BookStore;Trusted_Connection=True;MultipleActiveResultSets=true"
    }
}

這個寫法與官方教程不同,官方是以.DbMigrator.Host專案為啟動專案,並且使用專案中的中appsettings.json檔案進行遷移操作。
我們這是直接以Acme.BookStore.EntityFrameworkCore.DbMigrations為啟動專案,進行遷移操作。

資料遷移

  1. 選擇Acme.BookStore.EntityFrameworkCore.DbMigrations設為啟動專案。
  2. 啟動模板使用EF Core Code First Migrations建立和維護資料庫架構. 開啟選單工具 > NuGet包管理器下的程式包管理控制檯 (PMC).
  3. 選擇 Acme.BookStore.EntityFrameworkCore.DbMigrations 做為預設專案然後執行以下命令:
Add-Migration "Created_Book_Entity"
  1. 更新資料庫,執行以下命令:
Update-Database

至此Book實體及資料庫表建立成功。