DbContext:这里设置自定义连接字符串的写法过时了。参考连接MySql的写法。
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
"ConnectionStrings": { "Default": "Data Source=.;Initial Catalog=efcoretest;User ID=sa;Password=111111" },
Startup.cs
public void ConfigureServices(IServiceCollection services) { services.AddDbContext<DataMgrContext>();//注入数据库服务 //... }
使用
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
using Microsoft.EntityFrameworkCore; namespace dao { public class MysqlDataContext : DbContext { public MysqlDataContext(DbContextOptions<MysqlDataContext> options) : base(options) { } public DbSet<Payment> Payment { get; set; } } }
DAO实体
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 是自定义的接口
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
{ "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
//连接数据库,多数据库,直接新建多个DataContext就行了。 builder.Services.AddDbContext<MysqlDataContext>(options => { string connStr = builder.Configuration.GetConnectionString("MysqlContext") + ""; options.UseMySQL(connStr); }); #region 自定义服务 builder.Services.AddScoped<IPaymentService, PaymentService>(); #endregion
最后使用
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(); } }