前置条件

  MySQL 主从复制:https://www.cnblogs.com/fallTakeMan/p/14038888.html

环境说明

  本机开发环境:Win10,VS2019,.NetCoreSDK 3.1

  MySQL 服务器:192.168.187.66:3306(写),192.168.187.66:3307(读)

项目结构

  一个 webapi 项目,两个 dotnetcore 类库项目,ftm.EFcore 引用 ftm.Entity,ftm.api 引用 ftm.EFcore。

EntityFrameworkCore + MySQL 主从复制应用读写分离

 

项目说明

  ftm.EFcore 项目引用 nuget 包 Microsoft.EntityFrameworkCore(3.1.1),MySql.Data.EntityFrameworkCore(8.0.22)。

  创建三个文件 AppDbContext,IDbContextFactory,DbContextFactory。

 1 using ftm.Entity;
 2 using Microsoft.EntityFrameworkCore;
 3 
 4 
 5 namespace ftm.EFcore
 6 {
 7     public class AppDbContext : DbContext
 8     {
 9         private string connString = string.Empty;
10         /// <summary>
11         /// 传入数据库链接字符串构造 AppDbContext
12         /// </summary>
13         /// <param name="conn">数据库链接字符串</param>
14         public AppDbContext(string conn)
15         {
16             connString = conn;
17         }
18 
19         public DbSet<User> User { get; set; }
20 
21         protected override void OnConfiguring(DbContextOptionsBuilder options)
22         {
23             options.UseMySQL(connString);
24         }
25 
26         protected override void OnModelCreating(ModelBuilder builder)
27         {
28             builder.Entity<User>().HasKey(x => x.Id);
29         }
30     }
31 }
AppDbContext.cs

相关文章:

  • 2021-05-22
  • 2021-04-08
  • 2021-09-26
  • 2021-10-08
  • 2022-12-23
猜你喜欢
  • 2021-10-14
  • 2021-07-30
  • 2021-06-16
  • 2021-12-23
  • 2021-12-10
  • 2022-01-22
相关资源
相似解决方案