初学.net5,不想下载vs,就想用手头的vs code撸一下restful api,并且数据库选用mysql(因为便宜,方便),但是在链接数据库的时候遇到了不少坑,此文只简单记录一下。

建立.net 5程序,首先要下载.net 5 sdk。在vs code编写.net 5的程序,则要安装c#等扩展,以下是一个大佬写的,比较详细,按照这个步骤即可。

在安装好初步的环境后,就是创建restful api。是在目标文件夹下,在终端内输入:

dotnetnew webapi 或者dotnetnew webapi -o 指定文件夹 命令

然后你会发现相关项目文件就被这么创建好了。图片就不上了,自己看。

然后,要给vs code安装nuget扩展包,nuget是管理.net core程序扩展包的程序,类似于php的composer或者js的npm。

在vs code插件市场里搜索安装一下很简单的就安装上了。

安装好后,按ctrl+shift+p,输入NuGet Package Manager:Add Package

然后选择版本号。

此文选用的是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

33string connectionString = Configuration.GetSection("ConnectionStrings").GetSection("DefaultConnection").Value;

34 // Replace "YourDbContext" with the name of your own DbContext derived class.

35 services.AddDbContextPool(

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 { 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 Get()

{

return _db.Set().ToList();

}

}

}

最后,按ctrl+f5进行调试。

在地址后输入/api/controller/action,action和controller自己定。可以看到,数据读取成功。

原文:https://www.cnblogs.com/delgoh/p/14250311.html

dotnet vs code mysql_.net 5 用vs code链接mysql体验相关推荐

  1. docker4dotnet #3 在macOS上使用Visual Studio Code和Docker开发asp.net core和mysql应用

    .net猿遇到了小鲸鱼,觉得越来越兴奋.本来.net猿只是在透过家里那田子窗看外面的世界,但是看着海峡对岸的苹果园越来越茂盛,实在不想再去做一只宅猿了.于是,.net猿决定搭上小鲸鱼的渡轮到苹果园去看 ...

  2. 【开发环境】安装 Visual Studio Code 开发环境 ( 下载 Visual Studio Code 安装器 | Visual Studio Code )

    文章目录 一.下载 Visual Studio Code 安装器 二.安装 Visual Studio Code 一.下载 Visual Studio Code 安装器 进入 Visual Studi ...

  3. mac系统更新后code .命令打不开vs code

    mac系统更新后code .命令打不开vs code 前言:昨天mac系统更新后,出现了一些问题,首先,程序坞中找不到vs code这个软件,我还以为跟新后卸载了,有下了一个压缩包,就过在访达中的下载 ...

  4. IDEA使用git提交代码时,点了commit之后卡死在performing code analysis部分,或者performing code analysis结束后没有进入下一步操作。

    IDEA使用git提交代码时,点了commit之后卡死在performing code analysis部分,或者performing code analysis结束后没有进入下一步操作. 版权声明: ...

  5. IDEA 黄色警告 found duplicated code in this file finds duplicated code

    IDEA  编辑器发现重复的代码在文件中,会提示黄色警告 found duplicated code in this file  finds duplicated code 具体如下图 这个警告不影响 ...

  6. 線上 Android/Linux Kernel Source Code瀏覽 - Android/Linux Source Code Cross Reference

    線上 Android/Linux Kernel Source Code瀏覽 - Android/Linux Source Code Cross Reference http://hala01.com/ ...

  7. ef power tools mysql_使用 EF Power Tool Code Frist 生成 Mysql 实体

    使用 EF Power Tool Code Frist 生成 Mysql 实体 1,在要生成的项目上右键 2, 3, 4, 5,  生成后的效果 已知问题: 1,在Mysql数据表中 tinyint( ...

  8. 安卓后端mysql_后端Spring Boot+前端Android交互+MySQL增删查改(Java+Kotlin实现)

    1 前言&概述 这篇文章是基于这篇文章的更新,主要是更新了一些技术栈以及开发工具的版本,还有修复了一些Bug. 本文是SpringBoot+Android+MySQL的增删查改的简单实现,用到 ...

  9. refreshtoken用mysql_「SpringCloud」 Spring Security OAuth2 Mysql管理在线Token

    原标题:「SpringCloud」 Spring Security OAuth2 Mysql管理在线Token 前言:Spring Cloud 分布式中的登录如何可视化的管理目前下发的令牌.使用情况. ...

最新文章

  1. JavaScript正则表达式基础知识汇总
  2. Errors occurred during the build. Errors running builder 'JavaScript Validator' on project 'XXX'.
  3. Selenium+PhantomJS使用时报错原因及解决方案
  4. MySQL中表的操作
  5. Apache ZooKeeper - 使用Apache Curator操作ZK
  6. FICO年结完全手册
  7. struct多种声明定义写法的小结
  8. rabbitmq docker
  9. gm(GraphicsMagick)图片中文水印乱码问题
  10. mac系统linux不能ping外网,Mac上配置Linux网络适配器(NAT模式),无法ping通
  11. 计算机任务栏隐藏恢复,电脑看不到任务栏怎么办 电脑任务栏不见了如何恢复...
  12. Unity格子类三消游戏【物体下落】小细节(Unity萌新的备忘录)
  13. 我所热爱的多触摸系统 bill buxton
  14. ios申请企业开发者账号的代理_iOS企业级开发者账号申请
  15. CDR VBA X6中Exportbitmap函数的用法(导出图片)
  16. git撤回上一次的提交
  17. c# 使用Microsoft.Office.Interop.Excel 对Excel操作
  18. html背景图片不重叠铺满,css背景图片怎么铺满
  19. Java Map(hashmap)
  20. 社交舞 - 简介,释名,风格,舞步 - 金山词霸汉语 - HAPPY Life

热门文章

  1. android sd卡列目录文件_Android加载SD卡目录,文件夹遍历,图片设置,设置文件对应打开方式等...
  2. Git入门之上传本地项目至Github(一)
  3. [Android] 使用Matrix矩阵类对图像进行缩放、旋转、对比度、亮度处理
  4. 【数据结构与算法】之线性表的应用和操作
  5. 2020\Simulation_1\4.数字9
  6. 计算机中的进制和编码
  7. Insertion Sort Aizu - ALDS1_1_A
  8. 【嵌入式】Ubuntu20.04执行arm-linux-gc 没有那个文件或目录
  9. 【Android】Android之WiFi开发应用示例
  10. python加法器_[python bottle] 网页加法器