当前位置: 首页 > 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. 继续学习 

http://www.lqws.cn/news/105895.html

相关文章:

  • 『uniapp』把接口的内容下载为txt本地保存 / 读取本地保存的txt文件内容(详细图文注释)
  • WPS word 已有多级列表序号
  • 免费批量文件重命名软件
  • AI健康小屋+微高压氧舱:科技如何重构我们的健康防线?
  • KITTI数据集(计算机视觉和自动驾驶领域)
  • mobilnet v4 部署笔记
  • go语言基础|slice入门
  • C语言学习—数据类型20250603
  • 2025.6.3总结
  • Jpom:Java开发者的一站式自动化运维平台详解
  • Java编程之建造者模式
  • 深度学习入门Day2--鱼书学习(1)
  • 【Typst】4.导入、包含和读取
  • Spring AI Alibaba + Nacos 动态 MCP Server 代理方案
  • Playwright定位器详解:自动化测试的核心工具
  • 集合类基础概念
  • 2023年12月四级真题作文的分析总结
  • 704. 二分查找 (力扣)
  • 十五、【测试执行篇】异步与并发:使用 Celery 实现测试任务的后台执行与结果回调
  • GaLore:基于梯度低秩投影的大语言模型高效训练方法详解一
  • JSCH使用SFTP详细教程
  • Hadoop复习(九)
  • Linux 与 Windows:哪个操作系统适合你?
  • javascript 实战案例 二级联动下拉选框
  • godwork_ AT 5.2 摄影测量空三数据处理软件。
  • 星敏感器:卫星姿态测量的“星空导航仪”
  • 关系型数据库通过sql语句实现悲观锁与乐观锁
  • Golang 依赖注入:构建松耦合架构的关键技术
  • 原始数据去哪找?分享15个免费官方网站
  • 用AI(Deepseek)做了配色网站-功能介绍【欢迎体验】