.net5 console program uses EF to connect to MySQL database

Time:2022-7-31

1. Use nuget to download:

Microsoft.Extensions.Configuration.Json

Pomelo.EntityFrameworkCore.MySql

2. Create a 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 an entity class:

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace ConsoleApp1
{
    public class user2
    {
        [key] // primary key 
        [databasegenerated (databasegenerated option.identity)] // set auto increment
        public int mid { get; set; }
        public string uname { get; set; }

        public string memo { get; set; }
    }
}

4. Create a new JSON configuration file: appsettings.json, which is set to always copy.


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

5. Create a 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. Use

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 = "Zhang San" + I, memo = I};
                User2 Lisi = new user2 {uname = "Li Si" + 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!");
        }
    }
}

This is the end of this article about the method of using EF to connect mysql database in.Net5 console program. More related Net5 use EF to connect mysql content. Please search the previous articles of developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer in the future!

Recommended Today

JS generate guid method

JS generate guid method https://blog.csdn.net/Alive_tree/article/details/87942348 Globally unique identification(GUID) is an algorithm generatedBinaryCount Reg128 bitsNumber ofidentifier , GUID is mainly used in networks or systems with multiple nodes and computers. Ideally, any computational geometry computer cluster will not generate two identical guids, and the total number of guids is2^128In theory, it is difficult to make two […]