当前位置: 首页 > news >正文

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();}
}

4. 继续学习 

相关文章:

  • .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
  • 高性能MCU的MPU与Cache优化详解
  • 焊缝缺陷焊接缺陷识别分割数据集labelme格式5543张4类别
  • STM32单片机编程中标志变量的思想无处不在
  • CppCon 2014 学习:CHEAP, SIMPLE, AND SAFE LOGGING USING C++ EXPRESSION TEMPLATES
  • 《矛盾论》可以带给我们什么?
  • Gradle依赖管理全面指南:从基础到高级实践
  • 第一章 1.The Basic (CCNA)
  • Lua和JS的垃圾回收机制
  • 安全月报 | 傲盾DDoS攻击防御2025年5月简报
  • 【QT】认识QT
  • 帝可得 - 设备管理
  • 【C/C++】初步了解享元模式
  • 小黑一步步探索大模型应用:langchain中AgentExecutor的call方法初探demo(智能体调用)
  • React从基础入门到高级实战:React 高级主题 - React 微前端实践:构建可扩展的大型应用
  • AtCoder Beginner Contest 408(ABCDE)
  • 机器学习——随机森林算法
  • [蓝桥杯]上三角方阵
  • 5. Qt中.pro文件(1)
  • easylogger的移植使用
  • 西安网站/智能网站推广优化
  • 政府网站登录界面模板/搜索引擎成功案例分析
  • 成都网站建设全平台/百度公司注册地址在哪里
  • java开发网站轮播图怎么做/个人在百度上发广告怎么发
  • 无锡做网站服务/湘潭seo公司
  • 两学一做专栏网站/百度竞价广告投放