6

使用 EF 4.1 和 Mini-profiler 1.7。使用模型优先,从现有数据库中扫描。EF 生成一个派生自 ObjectContext/ObjectSet 的类,而不是 DbContext/DbSet。我找不到任何地方来控制它。

我尝试了流行的解决方案,但无济于事。

受挫后,我还尝试使用直接使用 ProfiledDbConnection 创建的显式 EntityConnection 直接创建我的 Context。我想绕过连接不是预期类型的​​任何机会。

public HomeController() {
try {
    string[] paths = new string[] { @"res://*/" };
    Assembly[] assys = new Assembly[] { Assembly.GetExecutingAssembly() };
    MetadataWorkspace mw = new MetadataWorkspace(paths, assys);
    string cnx = WebConfigurationManager.ConnectionStrings["XXXX"].ConnectionString;
    DbConnection cx = MvcMiniProfiler.Data.ProfiledDbConnection.Get(new SqlConnection(cnx), MiniProfiler.Current);
    //DbConnection cx = Database.DefaultConnectionFactory.CreateConnection(cnx);
    EntityConnection ec = new EntityConnection(mw, cx);
    db = new MyContextEntities(ec);
}
catch (Exception ex) {
    Trace.WriteLine("EDM failed: " + ex.Message);
    db = new MyContextEntities();
}
}

我已经验证了正确的路径。然而,当实际运行一个 LINQ 查询时,我们得到一个异常:

无法将“MvcMiniProfiler.Data.ProfiledDbConnection”类型的对象转换为“System.Data.SqlClient.SqlConnection”类型。

冒犯的说法是:

return query.ToList();

堆栈跟踪更有趣,因为显然 EF 内部的某些东西绝对需要 SqlConnection!

在 System.Data.SqlClient.SqlCommand.set_DbConnection(DbConnection 值) 在 System.Data.Common.DbCommand.set_Connection(DbConnection 值) 在 System.Data.Common.Utils.CommandHelper.SetStoreProviderCommandState(EntityCommand entityCommand, EntityTransaction entityTransaction, DbCommand storeProviderCommand)在 System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior 行为) 在 System.Data.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues) 在 System.Data.Objects.ObjectQuery 1.GetResults(Nullable1 forMergeOption)在 System.Data.Objects.ObjectQuery 1.System.Collections.Generic.IEnumerable.GetEnumerator() at System.Collections.Generic.List1..ctor(IEnumerable 1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable1 源)

显然,如果我改为给它一个 SqlConnection,一切都会很愉快。

这里发生了什么?这是怎么回事?也许它从未适用于 EDMX 案例?它是 ObjectContext 派生的这一事实有什么影响吗?

4

1 回答 1

1

升级 EF (4.1.10715.0) 和 MiniProfiler (1.9.1) 包并添加 MiniProfiler.EF (1.9.1) 包后,进入 App_Start 模块 (MiniProfiler.cs) 并输入以下内容,而不是ProfiledDbConnectionFactory代码:

MiniProfilerEF.Initialize();

一切都很好!

于 2011-09-23T17:43:21.173 回答