1. 程式人生 > 實用技巧 >.net 5 用vs code連結mysql體驗

.net 5 用vs code連結mysql體驗

初學.net5,不想下載vs,就想用手頭的vs code擼一下restful api,並且資料庫選用mysql(因為便宜,方便),但是在連結資料庫的時候遇到了不少坑,此文只簡單記錄一下。

建立.net 5程式,首先要下載.net 5 sdk。在vs code編寫.net 5的程式,則要安裝c#等擴充套件,以下是一個大佬寫的,比較詳細,按照這個步驟即可。

點這裡

在安裝好初步的環境後,就是建立restful api。是在目標資料夾下,在終端內輸入:

dotnet new webapi 或者dotnet new webapi -o 指定資料夾 命令

然後你會發現相關專案檔案就被這麼建立好了。圖片就不上了,自己看。

然後,要給vs code安裝nuget擴充套件包,nuget是管理.net core程式擴充套件包的程式,類似於php的composer或者js的npm。

在vs code外掛市場裡搜尋安裝一下很簡單的就安裝上了。

安裝好後,按ctrl+shift+p,輸入NuGet Package Manager:Add Package

再輸入Pomelo.EntityFrameworkCore.MySql

然後選擇版本號。

此文選用的是pomelo寫的程式集來連結mysql。當然還可以選擇其他的。

點這檢視其他

筆者比較蠢,在這個問題上糾結了很久,其實主要是將依賴版本當做了.net版本。沒能屢清楚.net 5 .net core 和entity framework core等的關係。而其實這裡的版本號是指的entity framework的版本號。

Entity Framework Core 是適用於 .NET 的新式物件資料庫對映器。 它支援 LINQ 查詢、更改跟蹤、更新和架構遷移。 EF Core 適用於很多資料庫,包括 SQL 資料庫(本地和 Azure)、SQLite、MySQL、PostgreSQL 和 Azure Cosmos DB。

以上摘自微軟官方。

所以,要選擇連結mysql的程式集,就要選擇安裝相關依賴版本的entity framework,否則就會報錯。

在安裝好環境後,修改appsettings.json如下:

{
  "ConnectionStrings": {
    "DefaultConnection": "server=ip address;userid=test;pwd=password;port=3306;database=dotnet_test;sslmode=none;CharSet=utf8;"
}, "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*" }

然後修改startup.cs,我的理解是入口檔案。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading.Tasks;
 5 using Microsoft.AspNetCore.Builder;
 6 using Microsoft.AspNetCore.Hosting;
 7 using Microsoft.AspNetCore.HttpsPolicy;
 8 using Microsoft.AspNetCore.Mvc;
 9 using Microsoft.Extensions.Configuration;
10 using Microsoft.Extensions.DependencyInjection;
11 using Microsoft.Extensions.Hosting;
12 using Microsoft.Extensions.Logging;
13 using Microsoft.OpenApi.Models;
14 using Microsoft.EntityFrameworkCore;
15 using Pomelo.EntityFrameworkCore.MySql.Infrastructure;
16 using webapi.Models;
17 
18 namespace webapi
19 {
20   public class Startup
21   {
22     public Startup(IConfiguration configuration)
23     {
24       Configuration = configuration;
25     }
26 
27     public IConfiguration Configuration { get; }
28 
29     // This method gets called by the runtime. Use this method to add services to the container.
30     public void ConfigureServices(IServiceCollection services)
31     {
32 
33       string connectionString = Configuration.GetSection("ConnectionStrings").GetSection("DefaultConnection").Value;
34       // Replace "YourDbContext" with the name of your own DbContext derived class.
35       services.AddDbContextPool<AppDb>(
36           dbContextOptions => dbContextOptions
37               .UseMySql(
38                   // Replace with your connection string.
39                   connectionString,
40                   // Replace with your server version and type.
41                   mySqlOptions => mySqlOptions
42                       .ServerVersion(new Version(5, 7, 31), ServerType.MySql)
43                       .CharSetBehavior(CharSetBehavior.NeverAppend)
44               )
45        );
46 
47       services.AddControllers();
48       services.AddSwaggerGen(c =>
49       {
50         c.SwaggerDoc("v1", new OpenApiInfo { Title = "webapi", Version = "v1" });
51       });
52     }
53 
54     // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
55     public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
56     {
57       if (env.IsDevelopment())
58       {
59         app.UseDeveloperExceptionPage();
60         app.UseSwagger();
61         app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "webapi v1"));
62       }
63 
64       app.UseHttpsRedirection();
65 
66       app.UseRouting();
67 
68       app.UseAuthorization();
69 
70       app.UseEndpoints(endpoints =>
71       {
72         endpoints.MapControllers();
73       });
74     }
75   }
76 }

再建立個models資料夾,新建一個數據庫上下文檔案,當然這個檔案也可以放在根目錄,請根據自己的習慣設定。我是在models資料夾下建立了appDb.cs檔案。

using Microsoft.EntityFrameworkCore;
namespace webapi.Models
{
  public class AppDb : DbContext
  {
    public DbSet<test> test { get; set; } //建立實體類新增Context中,我的表只有test這一個哦

    public AppDb(DbContextOptions options) : base(options)
    {
    }
  }
}

再在models下建立資料表的model檔案TestModels.cs。(資料庫和表請自己建立,這裡略去了。)

using System.ComponentModel.DataAnnotations;
namespace webapi.Models
{
  public class test
  {
    [Key]
    public int id { get; set; }
    [MaxLength(20)]
    public string name { get; set; }
    [MaxLength(300)]
    public string content { get; set; }
  }
}

最後是在controllers資料夾下建立控制器檔案TestControllers.cs

using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using webapi.Models;

namespace webapi.Controllers
{
  [Route("api/[controller]/[action]")]
  [ApiController]
  public class TestController : ControllerBase
  {
    private readonly AppDb _db;
    public TestController(AppDb db)
    {
      _db = db;
    }
    // GET api/test
    [HttpGet]
    public List<test> Get()
    {
      return _db.Set<test>().ToList();
    }
  }
}

最後,按ctrl+f5進行除錯。

在地址後輸入/api/controller/action,action和controller自己定。可以看到,資料讀取成功。