1. 程式人生 > 其它 >.net core .net6 webapi 連線mysql 8

.net core .net6 webapi 連線mysql 8

1.表結構:

CREATE TABLE `table2` (
  `id` BIGINT NOT NULL AUTO_INCREMENT,
  `myname` varchar(255) NOT NULL,
  `create_time` DATETIME  NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

2。新建一個名為“WebApiMySql”的 webapi專案。

3。nuget 下載“Pomelo.EntityFrameworkCore.MySql”包。

4。新建實體類,注意:類名表名保持一致:

using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

namespace WebApiMySql.Models
{
    public class table2
    {
        [Key] //主鍵 
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]  //設定自增
        public long id { get; set
; } public string myname { get; set; } public DateTime create_time { get; set; } } }

5。新建DbContext,注意:DbSet裡的屬性名和表名保持一致:

using Microsoft.EntityFrameworkCore;
using WebApiMySql.Models;

namespace WebApiMySql.Ctx
{
    public class w2DbContext: DbContext
    {
        //建構函式
        public
w2DbContext(DbContextOptions<w2DbContext> option) : base(option) { } //實體類名“table2”,本欄位屬性名“table2” public DbSet<table2> table2 { get; set; } } }

6.修改appsettings.json,增加連線字串:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "w2DbContext": "Server=128.0.0.33;Database=w2;uid=jojo;pwd=Yameking2022#;"
  }
}

7.修改 Program.cs, 在“var app = builder.Build();” 這一行的上面增加以下內容:

builder.Services.AddDbContext<w2DbContext>(option => {
    string connStr = builder.Configuration.GetConnectionString("w2DbContext");
    option.UseMySql(connStr, ServerVersion.AutoDetect(connStr), null);
});

8。新建api控制器“vvController”

using Microsoft.AspNetCore.Mvc;
using WebApiMySql.Ctx;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace WebApiMySql.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class vvController : ControllerBase
    {
        private readonly w2DbContext _w2db;

        public vvController(w2DbContext w2db)
        {
            _w2db=w2db;
        }
        // GET: api/<vvController>
        [HttpGet]
        public IEnumerable<string> Get()
        {
            try
            {
                var model= _w2db.table2.FirstOrDefault();
                if (model != null)
                {
                    return new string[] { "value1", model.myname };
                }
            }
            catch (Exception ex)
            {
                return new string[] { "value1", ex.Message };
            }

            return new string[] { "value1", "value2" };
        }
 
    }
}

即可使用。