posts - 609,  comments - 13,  views - 64万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

DbContext:这里设置自定义连接字符串的写法过时了。参考连接MySql的写法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
using WebApi.Models;
 
namespace WebApi.Data
{
    public class DataMgrContext : DbContext
    {
        public readonly static IConfiguration configuration;
        static DataMgrContext()
        {
            configuration = new ConfigurationBuilder()
            .SetBasePath(Environment.CurrentDirectory)
            .AddJsonFile("appsettings.json", true, true)
            .AddInMemoryCollection()
            .Build();
        }
        public static string connectionString
        {
            get { return configuration["ConnectionStrings:Default"]; }
        }
 
        public DataMgrContext(DbContextOptions<DataMgrContext> options)
            : base(options)
        {
        }
        public DataMgrContext() { }
         
        public DbSet<SysUser> SysUsers{ get; set; }
        public DbSet<Permission> Permissions { get; set; }
        public DbSet<Role> Roles { get; set; }
        public DbSet<RolePermission> RolePermissions { get; set; }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //映射数据库表名
            //modelBuilder.Entity<Role>().ToTable("Role");
        }
        protected override void OnConfiguring(DbContextOptionsBuilder options)
        {
            options.UseSqlServer(connectionString);
        }
    }
}

appSettings.json

1
2
3
"ConnectionStrings": {
    "Default": "Data Source=.;Initial Catalog=efcoretest;User ID=sa;Password=111111"
  },

Startup.cs

1
2
3
4
5
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<DataMgrContext>();//注入数据库服务
    //...
}

  使用

1
2
3
4
5
6
7
8
9
10
11
12
using (var db = new DataMgrContext())
{
    db.Blogs.Add(dto);
    db.SaveChanges();
}
 
//2
private readonly DataMgrContext db;
public BlogController(DataMgrContext context)
{
    db = context;
}


.Net Core连接Mysql数据库,以下是用的VS2022最新版,所以注入DbContext是在Program.cs中,大差不差。
引入NuGet包:Microsoft.EntityFrameworkCore,Microsoft.EntityFrameworkCore.Tools,Microsoft.Extensions.Configuration,MySql.EntityFrameworkCore
DAO层,DbContext

1
2
3
4
5
6
7
8
9
10
11
12
13
using Microsoft.EntityFrameworkCore;
namespace dao
{
    public class MysqlDataContext : DbContext
    {
        public MysqlDataContext(DbContextOptions<MysqlDataContext> options)
           : base(options)
        {
             
        }
        public DbSet<Payment> Payment { get; set; }
    }
}

 DAO实体

1
2
3
4
5
6
7
8
9
10
11
12
using System.ComponentModel.DataAnnotations.Schema;
namespace dao
{
    [Table("payment")]
    public class Payment
    {
        [Column("id")]
        public int Id { get; set; }
        [Column("serial")]
        public string? Serial { get; set; }
    }
}

 DAO Service,IPaymentService 是自定义的接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
namespace dao
{
    public class PaymentService : IPaymentService
    {
        private MysqlDataContext _mysqlDataContext;
        public PaymentService(MysqlDataContext mysqlDataContext)
        {
            _mysqlDataContext = mysqlDataContext;
        }
        public List<Payment> GetList()
        {
            return _mysqlDataContext.Payment.ToList();
        }
    }
}

  Web项目 appsettings.json

1
2
3
4
5
6
7
8
9
10
11
12
13
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "Default": "默认连接字符串,也可使用新的,支持多库",
    "MysqlContext": "server=localhost;port=3306;database=springcloudtest;uid=root;pwd=root123;CharSet=utf8;SslMode=none;AllowPublicKeyRetrieval=True;"
  }
}

  Web项目 Program.cs

1
2
3
4
5
6
7
8
9
10
//连接数据库,多数据库,直接新建多个DataContext就行了。
builder.Services.AddDbContext<MysqlDataContext>(options =>
{
    string connStr = builder.Configuration.GetConnectionString("MysqlContext") + "";
    options.UseMySQL(connStr);
});
 
#region 自定义服务
builder.Services.AddScoped<IPaymentService, PaymentService>();
#endregion

  最后使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class HomeController : Controller
{
    private IPaymentService _paymentService;
    public HomeController(IPaymentService paymentService)
    {
        _paymentService = paymentService;
    }
    public IActionResult Index()
    {
        var list = _paymentService.GetList();
        ViewData["list"] = list;
        return View();
    }
}

  

posted on   邢帅杰  阅读(603)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示