Abp vNext+SqlServer+MySql
目前项目使用的是 ABP vNext 版本 8.2.0 加上 SQL Server。由于业务需求,我们需要与 MySQL 数据库进行对接,这意味着项目的主要功能将继续使用 SQL Server,而部分特定功能将需要与 MySQL 数据库交互。
步骤1. 在项目“XXX.XXX.EntityFrameworkCore”中安装MySql包
dotnet add package Volo.Abp.EntityFrameworkCore.MySql
dotnet add package Pomelo.EntityFrameworkCore.MySql
步骤 2: 配置连接字符串
在 appsettings.json
文件中添加 MySQL 的连接字符串
{ "ConnectionStrings": { "Default": "Server=(localdb)\\mssqllocaldb;Database=AbpDb;Trusted_Connection=True;MultipleActiveResultSets=true", "MySql": "Server=localhost;Port=3306;Database=mydatabase;Uid=myusername;Pwd=mypassword;" }, ... }
步骤 3: 创建 DbContext
public class MySqlDbContext : AbpDbContext<MySqlDbContext> { public MySqlDbContext(DbContextOptions<MySqlDbContext> options) : base(options) { } public DbSet<AppStudent> AppStudents { get; set; } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); builder.Entity<AppStudent>(b => { b.ToTable("AppStudent"); b.ConfigureByConvention(); }); } }
步骤 4: 注册 DbContext
在“XXXX.XXX.EntityFrameworkCore”中找到“XXXXEntityFrameworkCoreModule”
public override void ConfigureServices(ServiceConfigurationContext context) { var configuration = context.Services.GetConfiguration(); context.Services.AddAbpDbContext<TwinsDbContext>(options => { /* Remove "includeAllEntities: true" to create * default repositories only for aggregate roots */ options.AddDefaultRepositories(includeAllEntities: true); }); context.Services.AddDbContext<MySqlDbContext>(options => { options.UseMySql( configuration.GetConnectionString("MySql"), ServerVersion.AutoDetect(configuration.GetConnectionString("MySql"))); }); Configure<AbpDbContextOptions>(options => { /* The main point to change your DBMS. * See also TwinsMigrationsDbContextFactory for EF Core tooling. */ options.UseSqlServer(); }); }
步骤 5: 使用 DbContext
public class AppStudent: Entity<int> { public virtual string Name{ get; set; } public virtual int Age{ get; set; } }
public interface IAppStudentRepository : IRepository<AppStudent, int> { Task<List<AppStudent>> GetByNameAsync(string name); }
public class AppStudentRepository : EfCoreRepository<MySqlDbContext, AppStudent, int>, { public AppStudentRepository(IDbContextProvider<MySqlDbContext> dbContextProvider) : base(dbContextProvider) { } public async Task<List<AppStudent>> GetByNameAsync(string name) { var dbSet = await GetDbSetAsync(); return dbSet.AsEnumerable().Where(c => c.Name== name).ToList(); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App