c# – MvcMiniProfiler无法转换EFProfiledDbConnection类型的对象

前端之家收集整理的这篇文章主要介绍了c# – MvcMiniProfiler无法转换EFProfiledDbConnection类型的对象前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试将MvcMiniProfiler集成到我的asp.net mvc实体framewok项目中.第一次Web请求时一切正常,但是在其他请求中给出了异常.

我的项目是
MVC 3
实体框架4.1(DatabaseFirst POCO Generator DbContext)
MvcMiniProfiler.dll 1.9.0.0
MvcMiniProfiler.EntityFramework.dll 1.9.1.0
我从Nu-Get安装了MvcMiniProfiler

下面添加到global.asax

protected void Application_BeginRequest()
    {
        if (Request.IsLocal)
        {
            MvcMiniProfiler.MiniProfiler.Start();
            MiniProfilerEF.Initialize();       
        }
    }

下面添加到web.config

<system.data>
    <DbProviderFactories>
      <remove invariant="MvcMiniProfiler.Data.ProfiledDbProvider" />
      <add name="MvcMiniProfiler.Data.ProfiledDbProvider" invariant="MvcMiniProfiler.Data.ProfiledDbProvider" description="MvcMiniProfiler.Data.ProfiledDbProvider" type="MvcMiniProfiler.Data.ProfiledDbProviderFactory,MvcMiniProfiler,Version=1.8.0.0,Culture=neutral,PublicKeyToken=b44f9351044011a3" />
    </DbProviderFactories>
  </system.data>

我得到了这个例外

System.InvalidCastException was unhandled by user code
  Message=Unable to cast object of type 'MvcMiniProfiler.Data.EFProfiledDbConnection' to type 'System.Data.sqlClient.sqlConnection'.
  Source=System.Data
  StackTrace:
       at System.Data.sqlClient.sqlCommand.set_DbConnection(DbConnection value)
       at System.Data.Common.DbCommand.set_Connection(DbConnection value)
       at MvcMiniProfiler.Data.ProfiledDbCommand.set_DbConnection(DbConnection value) in C:\Users\sam\Desktop\mvc-mini-profiler\MvcMiniProfiler\Data\ProfiledDbCommand.cs:line 118
       at System.Data.Common.DbCommand.set_Connection(DbConnection value)
       at System.Data.Common.Utils.CommandHelper.SetStoreProviderCommandState(EntityCommand entityCommand,EntityTransaction entityTransaction,DbCommand storeProviderCommand)
       at System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand,CommandBehavior behavior)
       at System.Data.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context,ObjectParameterCollection parameterValues)

EF调用中发生异常

ModaEntitiesWrapper.GetInstance().Articles
               .AsNoTracking()
               .Where(p => p.StatusId == 1).ToList();

如果我将Web.Config中MvcMiniProfiler.Data.ProfiledDbProvider的版本从1.8.0.0更改为1.9.0.0
MiniProfilerEF.Initialize()调用中出现了一种新类型的异常.

System.IndexOutOfRangeException was unhandled by user code
  Message=The given DataRow is not in the current DataRowCollection.
  Source=System.Data
  StackTrace:
       at System.Data.DataRowCollection.Remove(DataRow row)
       at MvcMiniProfiler.MiniProfilerEF.Initialize()

解决方法

也许这会有所帮助.移动MiniProfilerEF.Initialize();到Application_Start()方法的顶部.请注意,在EF 4.1及更高版本中,调用方法应为MiniProfilerEF.Initialize_EF42();代替.
protected void Application_Start() {
    Logger.Info("Application start");
    MiniProfilerEF.Initialize_EF42();
    // ...
}

猜你在找的C#相关文章