.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("Hello World!");
        }
    }
}

到此這篇關於.NET5控制臺程序使用EF連接MYSQL數據庫的方法的文章就介紹到這瞭,更多相關.NET5使用EF連接MYSQL內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: