在ASP.NET Core 3中映射Decimal类型到MySQL,你需要进行以下步骤:
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Pomelo.EntityFrameworkCore.MySql
dotnet add package MySql.Data.EntityFrameworkCore
using Microsoft.EntityFrameworkCore;
using Pomelo.EntityFrameworkCore.MySql.Infrastructure;
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext(options =>
options.UseMySql(Configuration.GetConnectionString("DefaultConnection"),
mysqlOptions =>
{
mysqlOptions.ServerVersion(new Version(8, 0, 21), ServerType.MySql);
})
);
}
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations.Schema;
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions options) : base(options)
{
}
public DbSet YourModels { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// 对应MySQL中的DECIMAL(18,2)类型
modelBuilder.Entity().Property(x => x.YourDecimalProperty).HasColumnType("DECIMAL(18,2)");
}
}
[Table("YourTable")]
public class YourModel
{
public int Id { get; set; }
public decimal YourDecimalProperty { get; set; }
}
{
"ConnectionStrings": {
"DefaultConnection": "your-connection-string"
}
}
private readonly ApplicationDbContext _context;
public YourController(ApplicationDbContext context)
{
_context = context;
}
public IActionResult YourAction()
{
var yourModels = _context.YourModels.ToList();
// 其他操作
}
这样就完成了在ASP.NET Core 3中映射Decimal类型到MySQL的解决方法。你可以根据自己的需求修改DECIMAL的精度和小数位数。