.NET CORE .NET5 控制台程序使用EF连接MYSQL

.NET5控制台程序使用EF连接MYSQL

 

1.使用nuget下载:

Microsoft.Extensions.Configuration.Json

Pomelo.EntityFrameworkCore.MySql

 

2.数据库中创建好表:

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.新建实体类:

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; }
    }
}

4.新建一个json配置文件:appsettings.json,设置为始终复制。

{
  "ConnectionStrings": {
    "Default": "Server=127.0.0.1;Database=wdb;charset=utf8;uid=root;pwd=some;"
  }
}

5.新建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);
        }        
    }
}

6.使用

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("www.51dev.com!");
        }
    }
}

 

你可能感兴趣的