问题描述: 当尝试使用ASP.NET Core Web API连接到MariaDB数据库时,出现连接失败的问题。需要提供解决方案,并附带代码示例。
解决方法:
确保已安装MariaDB数据库,并且数据库已启动。
在ASP.NET Core Web API项目中,安装以下包:
在appsettings.json
文件中添加数据库连接字符串:
"ConnectionStrings": {
"DefaultConnection": "Server=127.0.0.1;Database=YourDatabaseName;Uid=YourUsername;Pwd=YourPassword;"
}
Startup.cs
文件中进行以下配置:using Microsoft.EntityFrameworkCore;
using Pomelo.EntityFrameworkCore.MySql.Infrastructure;
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext(opt =>
opt.UseMySql(Configuration.GetConnectionString("DefaultConnection"), mySqlOptions =>
mySqlOptions.ServerVersion(new Version(10, 4, 11), ServerType.MariaDb)
)
);
}
DbContext
的类,用于处理与数据库的交互:using Microsoft.EntityFrameworkCore;
public class YourDbContext : DbContext
{
public YourDbContext(DbContextOptions options) : base(options)
{
}
public DbSet YourEntities { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// 配置实体映射
}
}
public class YourEntity
{
public int Id { get; set; }
public string Name { get; set; }
}
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
[ApiController]
[Route("api/[controller]")]
public class YourController : ControllerBase
{
private readonly YourDbContext _context;
public YourController(YourDbContext context)
{
_context = context;
}
[HttpGet]
public IEnumerable Get()
{
return _context.YourEntities.ToList();
}
}
现在,你可以尝试运行ASP.NET Core Web API项目,并尝试连接到MariaDB数据库了。