一、在类中重写OnConfiguring方法
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _01_EF_Enviroment
{
public class MyDBContext :DbContext
{
public DbSet Book { get; set; }
public DbSet Person { get; set; }
public DbSet Dogs { get; set; }
//这里是配置
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//DbContextOptionsBuilder注入
base.OnConfiguring(optionsBuilder);
//设置连接字符串
optionsBuilder.UseSqlServer("server=localhost;uid=sa;pwd=123456;database=demo1_Enviroment;");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//注入ModelBuilder
base.OnModelCreating(modelBuilder);
//获取当前程序集默认的是查找所有继承了IEntityTypeConfiguration的类
modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);
}
}
}
二、代码中用DbContextOptionBuilder定义
DbContextOptionsBuilder dbContextOptions = new DbContextOptionsBuilder();
dbContextOptions.UseMySql(strConnStr, ServerVersion.AutoDetect(strConnStr))
.LogTo(Console.WriteLine, LogLevel.Information)
.EnableSensitiveDataLogging()
.EnableDetailedErrors();
dbContext = new EFDbContext(dbContextOptions.Options);
详细步骤:
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 { 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数据库的方法 - 百度文库 (baidu.com)
(131条消息) EFCore——控制台搭建EFCore开发环境(1)_有诗亦有远方的博客-CSDN博客_efcore 控制台