Entity Framework Core 打印SQL语句

先建个表

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[students](
    [stu_id] [INT] IDENTITY(1,1) NOT NULL,
    [stu_name] [NVARCHAR](20) NULL,
    [stu_gender] [CHAR](1) NULL,
    [stu_phone] [VARCHAR](15) NULL,
    [stu_birthday] [DATE] NULL,
 CONSTRAINT [PK_students] PRIMARY KEY CLUSTERED 
(
    [stu_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

然后创建个.NET CORE 3 项目,NuGet安装

 

 在“程序包管理控制台中”执行

Scaffold-DbContext "Data Source=localhost;Initial Catalog=数据库名;User ID=用户名;Password=密码" Microsoft.EntityFrameworkCore.SqlServer -OutputDir EfModels

这里使用的是DB First模式,如果数据库还有更新,我们可以增加一个参数(-Force),这样可以更新

Scaffold-DbContext "Data Source=localhost;Initial Catalog=数据库名;User ID=用户名;Password=密码" Microsoft.EntityFrameworkCore.SqlServer -OutputDir EfModels -Force

在项目中就有了,如图

 

 添加两个类

 1     public class EFLoggerProvider : ILoggerProvider
 2     {
 3         public ILogger CreateLogger(string categoryName) => new EFLogger(categoryName);
 4         public void Dispose() { }
 5     }
 6 
 7     public class EFLogger : ILogger
 8     {
 9         private readonly string categoryName;
10 
11         public EFLogger(string categoryName) => this.categoryName = categoryName;
12 
13         public bool IsEnabled(LogLevel logLevel) => true;
14 
15         public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
16         {
17             //ef core执行数据库查询时的categoryName为Microsoft.EntityFrameworkCore.Database.Command,日志级别为Information
18             if (categoryName == "Microsoft.EntityFrameworkCore.Database.Command"
19                     && logLevel == LogLevel.Information)
20             {
21                 var logContent = formatter(state, exception);
22                 //TODO: 拿到日志内容想怎么玩就怎么玩吧
23                 Console.WriteLine();
24                 Console.ForegroundColor = ConsoleColor.Green;
25                 Console.WriteLine(logContent);
26                 Console.ResetColor();
27             }
28         }
29         public IDisposable BeginScope<TState>(TState state) => null;
30     }
View Code

我这里是控制台程序,在ResearchContext中稍作修改就可以了

1 var loggerFactory = new LoggerFactory();
2                 loggerFactory.AddProvider(new EFLoggerProvider());
3 optionsBuilder.UseSqlServer("连接字符串,可从配置文件中读取")
4                               .UseLoggerFactory(loggerFactory);
View Code

如果是web项目,可以在Startup的ConfigureService中配置

1 services.AddDbContext<YourDbContext>(r => {
2                 //使用ef core mysql 连接
3                 var loggerFactory = new LoggerFactory();
4                 loggerFactory.AddProvider(new EFLoggerProvider());
5  
6                 r.UseSqlServer(Configuration.GetConnectionString("你的连接字符串"))
7                     .UseLoggerFactory(loggerFactory);
8             });
View Code

我们这里是控制台程序,Main方法中的代码

static async Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");
Students stu = new Students { StuGender = "0", StuBirthday = DateTime.Now, StuName = "CHAUVET", StuPhone = "17655889687" };
            using (var context = new ResearchContext())
            {
               var id =  await context.Students.AddAsync(stu);
                await context.SaveChangesAsync();

                var obj = await context.Students.Where(p=>p.StuName=="CHAUVET").ToListAsync();

                Console.WriteLine(obj[0].StuName);
            }
        }

效果如图

 主要参考:https://www.cnblogs.com/hualiu0/p/10826392.html

posted @ 2020-04-18 13:03  静文·辅神  阅读(2761)  评论(0编辑  收藏  举报