1 新建实体
using System;
using Volo.Abp.Domain.Entities.Auditing;
namespace Acme.BookStore
{
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; }
protected Book()
{
}
public Book(Guid id, string name, BookType type, DateTime publishDate, float price)
:base(id)
{
Name = name;
Type = type;
PublishDate = publishDate;
Price = price;
}
}
}
2 新建常量
namespace Acme.BookStore
{
public enum BookType
{
Undefined,
Adventure,
Biography,
Dystopia,
Fantastic,
Horror,
Science,
ScienceFiction,
Poetry
}
}
3 ABP Architecture(ABP 项目架构), 只有明白这个项目架构,才能清楚的知道什么项目该处理什么事情
4 将Book实体添加到DbContext中
EF Core需要你将实体和 DbContext
建立关联.最简单的做法是在 Acme.BookStore.EntityFrameworkCore
项目的 BookStoreDbContext
类中添加DbSet属性.如下所示:
public class BookStoreDbContext : AbpDbContext<BookStoreDbContext>
{
public DbSet<Book> Book { get; set; }
...
}
5 配置你的Book实体
在 Acme.BookStore.EntityFrameworkCore
项目中打开 BookStoreDbContextModelCreatingExtensions.cs
文件,并将以下代码添加到 ConfigureBookStore
方法的末尾以配置Book实体:
builder.Entity<Book>(b =>
{
b.ToTable(BookStoreConsts.DbTablePrefix + "Book", BookStoreConsts.DbSchema);
b.ConfigureByConvention(); //auto configure for the base class props
b.Property(x => x.Name).IsRequired().HasMaxLength(128);
});
6 添加新的Migration并更新数据库
- 6.1 打开 程序包管理器控制台
(Package Manager Console)
(PMC) (工具/Nuget包管理器菜单)
- 6.2 选择
Acme.BookStore.EntityFrameworkCore.DbMigrations
作为默认的项目然后执行下面的命令:
Add-Migration "Created_Book_Entity"
这样就会在 Migrations
文件夹中创建一个新的migration类.
- 6.3 然后执行 Update-Database 命令更新数据库结构:
Update-Database
7 添加示例数据,打开SSMS,执行下面的语句
INSERT INTO AppBook (Id,CreationTime,[Name],[Type],PublishDate,Price) VALUES
('f3c04764-6bfd-49e2-859e-3f9bfda6183e', '2018-07-01', '1984',3,'1949-06-08','19.84')
INSERT INTO AppBook (Id,CreationTime,[Name],[Type],PublishDate,Price) VALUES
('13024066-35c9-473c-997b-83cd8d3e29dc', '2018-07-01', 'The Hitchhiker`s Guide to the Galaxy',7,'1995-09-27','42')
INSERT INTO AppBook (Id,CreationTime,[Name],[Type],PublishDate,Price) VALUES
('4fa024a1-95ac-49c6-a709-6af9e4d54b54', '2018-07-02', 'Pet Sematary',5,'1983-11-14','23.7')