Asp.net MVC4 CodeFirst 使用EFTracingProvider

一、关于EFTracingProvider

EFTracingProvider相关信息见作者博客:关于EFTracingProvider

EFTracingProvider Demo下载地址:Tracing and Caching Provider Wrappers for Entity Framework 4

EFTracingProvider 相关问题讨论:DISCUSSIONS

EFTracingProvider Nuget安装:Entity Framework Tracing Provider 1.0.0

二、如何在CodeFirst模式下使用EFTracingProvider

通过查阅的资料发现,给出的EFTracingProvider示例大都是在模型优先的模式下使用的,少有代码优先模式下的例子,不过好在在(DISCUSSIONS)里发现了答案。

现将CodeFirst模式下的使用方法做一总结,以供参考。

1、Web.config配置,添加如下配置。

  <appSettings>

	<!--turn on/off EFTracing-->
	<add key="EFTracingProvider:Enabled" value="true" />
	<!-- write log messages to the console. -->
	<add key="EFTracingProvider.logToConsole" value="false" />
	<!-- append log messages to the specified file -->
	<add key="EFTracingProvider.logToFile" value="E:\sqllog.txt" />
	  
  </appSettings>
  <system.data>
	<DbProviderFactories>
		<add name="EF Caching Data Provider" invariant="EFCachingProvider" description="Caching Provider Wrapper" type="EFCachingProvider.EFCachingProviderFactory, EFCachingProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=def642f226e0e59b" />
		<add name="EF Tracing Data Provider" invariant="EFTracingProvider" description="Tracing Provider Wrapper" type="EFTracingProvider.EFTracingProviderFactory, EFTracingProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=def642f226e0e59b" />
		<add name="EF Generic Provider Wrapper" invariant="EFProviderWrapper" description="Generic Provider Wrapper" type="EFProviderWrapperToolkit.EFProviderWrapperFactory, EFProviderWrapperToolkit, Version=1.0.0.0, Culture=neutral, PublicKeyToken=def642f226e0e59b" />
	</DbProviderFactories>
  </system.data>

2、Global文件配置,在Application_Start()中添加如下代码:

            //当启用EFTracingProvider时,不进行初始化数据库
            if (string.Equals(ConfigurationManager.AppSettings["EFTracingProvider:Enabled"], "true", StringComparison.InvariantCultureIgnoreCase))
            {
                Database.SetInitializer<JYZSContext>(null);
                JYZSContext.TraceEnabled = true;
            }
            else
            {
                Database.SetInitializer<JYZSContext>(new JYZSInitializer());
            }

3、修改你的DbContext,主要是将构造函数中的DbConnection类型链接改为TracingConnection类型的链接。

        #region Trace Mechanics

        public static bool TraceEnabled = false;

        public JYZSContext() : this("JYZSConnection") { }

        public JYZSContext(string nameOrConnectionString)
            : base(CreateConnection(nameOrConnectionString), true)
        {
            if (TraceEnabled)
            {
                ((IObjectContextAdapter)this).ObjectContext.EnableTracing();
            }
        }

        private static DbConnection CreateConnection(string nameOrConnectionString)
        {
            EFTracingProviderFactory.Register();

            ConnectionStringSettings connectionStringSetting =
                ConfigurationManager.ConnectionStrings[nameOrConnectionString];
            string connectionString;
            string providerName;

            if (connectionStringSetting != null)
            {
                connectionString = connectionStringSetting.ConnectionString;
                providerName = connectionStringSetting.ProviderName;
            }
            else
            {
                providerName = "System.Data.SqlClient";
                connectionString = nameOrConnectionString;
            }

            return CreateConnection(connectionString, providerName);
        }

        private static DbConnection CreateConnection(string connectionString, string providerInvariantName)
        {
            DbConnection connection = null;
            if (TraceEnabled)
            {
                connection = CreateTracingConnection(connectionString, providerInvariantName);
            }
            else
            {
                DbProviderFactory factory = DbProviderFactories.GetFactory(providerInvariantName);
                connection = factory.CreateConnection();
                connection.ConnectionString = connectionString;
            }
            return connection;
        }

        private static EFTracingConnection CreateTracingConnection(string connectionString, string providerInvariantName)
        {

            string wrapperConnectionString =
                String.Format(@"wrappedProvider={0};{1}", providerInvariantName, connectionString);

            EFTracingConnection connection =
                new EFTracingConnection
                {
                    ConnectionString = wrapperConnectionString
                };
            //hook up logging here
            connection.CommandFinished +=
                (sender, args) => Console.WriteLine(args.ToTraceString());
            
            return connection;
        }

        #endregion

三、总结说明

以上代码是在我的项目中整理出来的,使用时注意修改链接字符串名称,并根据你的需要修改配置。

以代码中配置为例,当运行程序时,就可以在 E:\sqllog.txt 查看到EF生成的SQL语句了。实在是方便极了。

你可能感兴趣的:(Provider)