1. Use nuget to download:
2. Create a good table in the database:
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;
3. Create a new entity class:
using ; using ; namespace ConsoleApp1 { public class user2 { [Key] //Primary key [DatabaseGenerated()] //Settings are increased public int mid { get; set; } public string uname { get; set; } public string memo { get; set; } } }
4. Create a new json configuration file:, set to always copy.
{ "ConnectionStrings": { "Default": "Server=127.0.0.1;Database=wdb;charset=utf8;uid=root;pwd=some;" } }
5. Create a new DbContext
using ; using ; using ; namespace ConsoleApp1 { public class DefaultDbContext : DbContext { private IConfiguration configuration; public DefaultDbContext() { configuration = new ConfigurationBuilder().SetBasePath(()).AddJsonFile("").Build(); } public DbSet<user2> user2 { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { string connStr = ("Default"); (connStr, (connStr),null); } } }
6. Use
using ConsoleApp1; using System; using ; namespace Net5ConsoleMySql { class Program { static void Main(string[] args) { try { DefaultDbContext context = new DefaultDbContext(); Random rnd = new Random(); string i = (1000, 9000).ToString(); user2 zhangsan = new user2 { uname = "Zhang San" + i, memo = i }; user2 lisi = new user2 { uname = "Li Si" + i, memo = i }; context.(zhangsan, lisi); (); var users = context.(); foreach (var user in users) { ($"{} {} {}"); } } catch (Exception ex) { ($"EX: {} "); if ( != null) { ($"INNER EX: {} "); } } ("Hello World!"); } } }
This is the article about how to use EF to connect to MYSQL database for .NET5 console programs. For more related content related to .NET5 using EF to connect to MYSQL, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!