目前项目使用的是 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(); } }
标签:vNext,SqlServer,options,Abp,EntityFrameworkCore,context,MySql,Server,public From: https://www.cnblogs.com/wz122889488/p/18366151