EF Core继承DbContext的上下文类参考,包含跟踪sql日志

using Comm;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using Microsoft.Extensions.Logging.Debug;
using Microsoft.Extensions.Logging.TraceSource;
using Model.Entity;
using Model.View;
using System;
using System.Linq;

namespace DAL
{
    public class DataContext : DbContext
    {
        public DataContext(DbContextOptions options)
            : base(options)
        {
        }
 

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            // optionsBuilder.UseInternalServiceProvider()            
            //string connection = "";
            //optionsBuilder.UseSqlServer(connection);
            //optionsBuilder.UseSqlServer(optionsBuilder.Options.Extensions.)          

            //this.Database.SetCommandTimeout(60);

            //设置不跟踪所有查询  2019-8-4 15:24:33 add
            optionsBuilder.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);

            //参数记录 2019-8-4 15:24:33 add
            optionsBuilder.EnableSensitiveDataLogging();

            var loggerFactory = new LoggerFactory();
            //  loggerFactory.AddProvider(new ConsoleLoggerProvider((category, level)
            //=> category == DbLoggerCategory.Database.Command.Name
            //   && level == LogLevel.Information, true));
            
            //记录sql生成
            loggerFactory.AddDebug(
                (categoryName, logLevel) =>
                //(logLevel == LogLevel.Debug) && (categoryName == DbLoggerCategory.Database.Command.Name)
                logLevel == LogLevel.Information
                && categoryName == DbLoggerCategory.Database.Command.Name
                //|| (categoryName == DbLoggerCategory.Query.Name)
                //|| (categoryName == DbLoggerCategory.Model.Name)
                );

            optionsBuilder.UseLoggerFactory(loggerFactory);
        }

        //protected override void OnModelCreating(ModelBuilder modelBuilder)
        //{
        //    //modelBuilder.Entity().Property("TenantId").HasField("_tenantId");
        //     Configure entity filters
        //    //modelBuilder.Entity().HasQueryFilter(b => EF.Property(b, "TenantId") == _tenantId);
        //    //modelBuilder.Entity().HasQueryFilter(p => p.DataState != (short)EDataState.Delete);
        //    //modelBuilder.Entity().HasQueryFilter(p => p.DataState != (short)EDataState.Delete);            
        //}

        public virtual DbSet Setting { get; set; }
        public virtual DbSet Media { get; set; }
        public virtual DbSet Student { get; set; }

    }

    

}

 

你可能感兴趣的:(EF,Core,EF,CORE)