1. 定义实体类
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. 在*.Domain
项目中自定义类继承接口IDataSeedContributor
public class BookStoreDataSeederContributor : IDataSeedContributor, ITransientDependency
{
private readonly IRepository<Book, Guid> _bookRepository;
private readonly IGuidGenerator _guidGenerator;
public BookStoreDataSeederContributor(
IRepository<Book, Guid> bookRepository,
IGuidGenerator guidGenerator)
{
_bookRepository = bookRepository;
_guidGenerator = guidGenerator;
}
public async Task SeedAsync(DataSeedContext context)
{
if (await _bookRepository.GetCountAsync() > 0)
{
return;
}
await _bookRepository.InsertAsync(
new Book(
id: _guidGenerator.Create(),
name: "1984",
type: BookType.Dystopia,
publishDate: new DateTime(1949, 6, 8),
price: 19.84f)
);
await _bookRepository.InsertAsync(
new Book(
id: _guidGenerator.Create(),
name: "The Hitchhiker's Guide to the Galaxy",
type: BookType.ScienceFiction,
publishDate: new DateTime(1995, 9, 27),
price: 42.0f
)
);
}
}
3. 在*.DbMigrator
项目中使用
在DbMigratorModule
类中的ConfigureServices
方法中增加以下代码
// Remove the contributor for migrator module
context.Services.RemoveAll(t => t.ImplementationType == typeof(IDataSeedContributor));
// Add custom data seed contributor
context.Services.AddTransient<IDataSeedContributor, BookStoreDataSeederContributor>();
4. 运行*.DbMigrator
项目将种子数据插入数据库
{
"_id" : BinData(3, "qzRKPNQ9njG7/Dn2DQs6vA=="),
"ConcurrencyStamp" : "e7d814f99be041c6aa9280fa6c8ae419",
"CreationTime" : ISODate("2020-06-28T12:19:37.793+0000"),
"CreatorId" : null,
"LastModificationTime" : null,
"LastModifierId" : null,
"Name" : "1984",
"Type" : NumberInt(3),
"PublishDate" : ISODate("1949-06-07T16:00:00.000+0000"),
"Price" : 19.84000015258789
}
{
"_id" : BinData(3, "VkmENDKl8bufpDn2DQs8Aw=="),
"ConcurrencyStamp" : "a8c74d60cd1240a1b6ac54042d8e0a27",
"CreationTime" : ISODate("2020-06-28T12:19:38.115+0000"),
"CreatorId" : null,
"LastModificationTime" : null,
"LastModifierId" : null,
"Name" : "The Hitchhiker's Guide to the Galaxy",
"Type" : NumberInt(7),
"PublishDate" : ISODate("1995-09-26T16:00:00.000+0000"),
"Price" : 42.0
}