ABP-Book Store Application中文讲解 - Part 7: Authors: Database Integration
ABP-Book Store Application中文讲解 - Part 7: Authors: Database Integration
1. 汇总
ABP-Book Store Application中文讲解-汇总-CSDN博客
2. 前一章
ABP-Book Store Application中文讲解 - Part 6: Authors: Domain Layer-CSDN博客
项目之间的引用关系。
目录
1. 注册Author
2. DB Migration
2.1 利用Package Manager Console
2.2 利用dotnet ef
3. 创建EfCoreAuthorRepository 实现IAuthorRepository
4. 继续学习
1. 注册Author
在Acme.BookStore.EntityFrameworkCore中的EntityFrameworkCore文件夹下的BookStoreDbContext.cs中添加如下代码:
public DbSet<Author> Authors { get; set; }
然后在同一个文件中的OnModelCreating中添加如下代码:
builder.Entity<Author>(b =>{b.ToTable(BookStoreConsts.DbTablePrefix + "Authors", BookStoreConsts.DbSchema);b.ConfigureByConvention();// auto configure for the base class propsb.Property(x => x.Name).IsRequired().HasMaxLength(AuthorConsts.MaxNameLength);// 创建非空字段,并设置字段最大长度b.HasIndex(x => x.Name);// 创建索引});
BookStoreDbContext.cs完成代码:
using Acme.BookStore.Authors;
using Acme.BookStore.Books;
using Microsoft.EntityFrameworkCore;
using Volo.Abp.AuditLogging.EntityFrameworkCore;
using Volo.Abp.BackgroundJobs.EntityFrameworkCore;
using Volo.Abp.Data;
using Volo.Abp.DependencyInjection;
using Volo.Abp.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.Modeling;
using Volo.Abp.FeatureManagement.EntityFrameworkCore;
using Volo.Abp.Identity;
using Volo.Abp.Identity.EntityFrameworkCore;
using Volo.Abp.OpenIddict.EntityFrameworkCore;
using Volo.Abp.PermissionManagement.EntityFrameworkCore;
using Volo.Abp.SettingManagement.EntityFrameworkCore;
using Volo.Abp.TenantManagement;
using Volo.Abp.TenantManagement.EntityFrameworkCore;namespace Acme.BookStore.EntityFrameworkCore;[ReplaceDbContext(typeof(IIdentityDbContext))]
[ReplaceDbContext(typeof(ITenantManagementDbContext))]
[ConnectionStringName("Default")]
public class BookStoreDbContext :AbpDbContext<BookStoreDbContext>,IIdentityDbContext,ITenantManagementDbContext
{/* Add DbSet properties for your Aggregate Roots / Entities here. */#region Entities from the modules/* Notice: We only implemented IIdentityDbContext and ITenantManagementDbContext* and replaced them for this DbContext. This allows you to perform JOIN* queries for the entities of these modules over the repositories easily. You* typically don't need that for other modules. But, if you need, you can* implement the DbContext interface of the needed module and use ReplaceDbContext* attribute just like IIdentityDbContext and ITenantManagementDbContext.** More info: Replacing a DbContext of a module ensures that the related module* uses this DbContext on runtime. Otherwise, it will use its own DbContext class.*///Identitypublic DbSet<IdentityUser> Users { get; set; }public DbSet<IdentityRole> Roles { get; set; }public DbSet<IdentityClaimType> ClaimTypes { get; set; }public DbSet<OrganizationUnit> OrganizationUnits { get; set; }public DbSet<IdentitySecurityLog> SecurityLogs { get; set; }public DbSet<IdentityLinkUser> LinkUsers { get; set; }public DbSet<IdentityUserDelegation> UserDelegations { get; set; }public DbSet<IdentitySession> Sessions { get; set; }// Tenant Managementpublic DbSet<Tenant> Tenants { get; set; }public DbSet<TenantConnectionString> TenantConnectionStrings { get; set; }public DbSet<Book> Books { get; set; }public DbSet<Author> Authors { get; set; }#endregionpublic BookStoreDbContext(DbContextOptions<BookStoreDbContext> options): base(options){}protected override void OnModelCreating(ModelBuilder builder){base.OnModelCreating(builder);/* Include modules to your migration db context */builder.ConfigurePermissionManagement();builder.ConfigureSettingManagement();builder.ConfigureBackgroundJobs();builder.ConfigureAuditLogging();builder.ConfigureIdentity();builder.ConfigureOpenIddict();builder.ConfigureFeatureManagement();builder.ConfigureTenantManagement();/* Configure your own tables/entities inside here *///builder.Entity<YourEntity>(b =>//{// b.ToTable(BookStoreConsts.DbTablePrefix + "YourEntities", BookStoreConsts.DbSchema);// b.ConfigureByConvention(); //auto configure for the base class props// //...//});builder.Entity<Book>(b =>{b.ToTable(BookStoreConsts.DbTablePrefix + "Books",BookStoreConsts.DbSchema);b.ConfigureByConvention(); //auto configure for the base class propsb.Property(x => x.Name).IsRequired().HasMaxLength(128);});builder.Entity<Author>(b =>{b.ToTable(BookStoreConsts.DbTablePrefix + "Authors", BookStoreConsts.DbSchema);b.ConfigureByConvention();// auto configure for the base class propsb.Property(x => x.Name).IsRequired().HasMaxLength(AuthorConsts.MaxNameLength);// 创建非空字段,并设置字段最大长度b.HasIndex(x => x.Name);// 创建索引});}
}
2. DB Migration
2.1 利用Package Manager Console
Tools --》 NuGet Package Manager --> Package Manager Console
如果利用VS的Add-Migration和Update-Databse,需要右击Acme.BookStore.EntityFrameworkCore设置为启动项(Set as Startup Project)。
Default project选择Acme.BookStore.EntityFrameworkCore,然后输入add-migr,敲Tab会自动补全Add-Migration 。然后输入Add_Authors,敲回车。
Add-Migration Add_Author
如果生成成功,可以利用一下命令更新DB
Update-Database
2.2 利用dotnet ef
如果以上命令生成失败,可以右击cme.BookStore.EntityFrameworkCore,选择Open in terminal,利用ef 生成。
dotnet ef migrations add Add_Authors
生成成功后,利用一下命令更新DB
dotnet ef database update
3. 创建EfCoreAuthorRepository
实现IAuthorRepository
在Acme.BookStore.EntityFrameworkCore中的EntityFrameworkCore文件夹下创建Authors目录,然后创建EfCoreAuthorRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Acme.BookStore.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;namespace Acme.BookStore.Authors;public class EfCoreAuthorRepository: EfCoreRepository<BookStoreDbContext, Author, Guid>,IAuthorRepository
{public EfCoreAuthorRepository(IDbContextProvider<BookStoreDbContext> dbContextProvider): base(dbContextProvider){}public async Task<Author> FindByNameAsync(string name){var dbSet = await GetDbSetAsync();return await dbSet.FirstOrDefaultAsync(author => author.Name == name);}public async Task<List<Author>> GetListAsync(int skipCount,int maxResultCount,string sorting,string filter = null){var dbSet = await GetDbSetAsync();return await dbSet.WhereIf(!filter.IsNullOrWhiteSpace(),author => author.Name.Contains(filter)).OrderBy(sorting).Skip(skipCount).Take(maxResultCount).ToListAsync();}
}