EF Core在控制台程序中使用

一、在类中重写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> Book { get; set; }
        public DbSet<Person> Person { get; set; }
        public DbSet<Dog> 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<EFDbContext> dbContextOptions = new DbContextOptionsBuilder<EFDbContext>();
    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> 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 控制台

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值