小编给大家分享一下.NET5控制台程序如何使用EF连接MYSQL数据库,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
使用nuget下载:
Microsoft.Extensions.Configuration.Json
Pomelo.EntityFrameworkCore.MySql
数据库中创建好表:
CREATE TABLE `user2` ( `mid` int NOT NULL AUTO_INCREMENT, `uname` varchar(45) NOT NULL, `memo` varchar(200) DEFAULT NULL, PRIMARY KEY (`mid`)) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
新建实体类:
using System.ComponentModel.DataAnnotations;using System.ComponentModel.DataAnnotations.Schema;namespace ConsoleApp1{ public class user2 { [Key] //主键 [DatabaseGenerated(DatabaseGeneratedOption.Identity)] //设置自增 public int mid { get; set; } public string uname { get; set; } public string memo { get; set; } }}
新建一个json配置文件:appsettings.json,设置为始终复制。
{ "ConnectionStrings": { "Default": "Server=127.0.0.1;Database=wdb;charset=utf8;uid=root;pwd=some;" }}
新建DbContext
using Microsoft.EntityFrameworkCore;using Microsoft.Extensions.Configuration;using System.IO;namespace ConsoleApp1{ public class DefaultDbContext : DbContext { private IConfiguration configuration; public DefaultDbContext() { configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").Build(); } public DbSet<user2> user2 { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { string connStr = configuration.GetConnectionString("Default"); optionsBuilder.UseMySql(connStr, ServerVersion.AutoDetect(connStr),null); } }}
使用
using ConsoleApp1;using System;using System.Linq;namespace Net5ConsoleMySql{ class Program { static void Main(string[] args) { try { DefaultDbContext context = new DefaultDbContext(); Random rnd = new Random(); string i = rnd.Next(1000, 9000).ToString(); user2 zhangsan = new user2 { uname = "张三" + i, memo = i }; user2 lisi = new user2 { uname = "李四" + i, memo = i }; context.user2.AddRange(zhangsan, lisi); context.SaveChanges(); var users = context.user2.ToList(); foreach (var user in users) { Console.WriteLine($"{user.mid} {user.uname} {user.memo}"); } } catch (Exception ex) { Console.WriteLine($"EX: {ex.Message} "); if (ex.InnerException != null) { Console.WriteLine($"INNER EX: {ex.InnerException.Message} "); } } Console.WriteLine("Hello World!"); } }}
以上是“.NET5控制台程序如何使用EF连接MYSQL数据库”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注编程网行业资讯频道!