使用带有实体框架代码优先和 ASP.NET MVC 3 和 mvc miniprofiler 的 SQL Server CE 时出现问题

Posted

技术标签:

【中文标题】使用带有实体框架代码优先和 ASP.NET MVC 3 和 mvc miniprofiler 的 SQL Server CE 时出现问题【英文标题】:Problem using SQL Server CE with Entity Framework code-first and ASP.NET MVC 3 and mvc miniprofiler 【发布时间】:2011-09-26 19:58:39 【问题描述】:

我正在尝试使用 C#、Entity Framework 4.0 代码优先和 SQL Server CE 以及自动脚手架创建一个 ASP.NET MVC 3 应用程序。在我尝试实际使用连接到 SQL Server CE 数据库的页面之前,一切正常。

我在 web.config 中的连接是这样的

<add name="BRX" connectionString="Data Source=|DataDirectory|BRX.sdf" providerName="System.Data.SqlServerCe.4.0"/>

我的模型类是这样的

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace BizRadioXInternal.Models

    public class KeyWordEmail
    
        [Key]
        public int KeywordEmailID  get; set; 
        public string Name  get; set; 
        public string Keyword  get; set; 
        public string Link  get; set; 
        public string EmailAddress  get; set; 
    

我的数据上下文类看起来像这样

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using BizRadioXInternal.Models;

namespace BizRadioXInternal.Models

    public class BRX : DbContext
    
        public virtual DbSet<KeyWordEmail> KeyWordEmails  get; set; 
    

每次我尝试访问涉及数据库的页面(如标准索引页面)时,都会出现以下错误

给定的程序集名称或代码库无效。 (例外来自 HRESULT: 0x80131047)

这是堆栈跟踪

[FileLoadException: The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)]
   System.Reflection.AssemblyName.nInit(RuntimeAssembly& assembly, Boolean forIntrospection, Boolean raiseResolveEvent) +0
   System.Reflection.AssemblyName..ctor(String assemblyName) +80
   System.Data.Entity.ModelConfiguration.Utilities.DbConnectionExtensions.GetProviderInvariantName(DbConnection connection) +312
   System.Data.Entity.ModelConfiguration.Utilities.DbConnectionExtensions.GetProviderInfo(DbConnection connection, DbProviderManifest& providerManifest) +63
   System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection) +157
   System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext) +62
   System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input) +117
   System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +407
   System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +18
   System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +62
   System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator() +15
   System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator() +40
   System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +315
   System.Linq.Enumerable.ToList(IEnumerable`1 source) +58
   BizRadioXInternal.Controllers.KeyWordEmailController.Index() in D:\Creative Plumbing\BusinessRadioX\BizRadioXInternal\BizRadioXInternal\BizRadioXInternal\Controllers\KeyWordEmailController.cs:21
   lambda_method(Closure , ControllerBase , Object[] ) +62
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +208
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
   System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +55
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263
   System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263
   System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +191
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343
   System.Web.Mvc.Controller.ExecuteCore() +116
   System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97
   System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
   System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37
   System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
   System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
   System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
   System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8963149
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184

我到底做错了什么?

更新:问题的根本原因似乎在 global.asax 文件中。我正在使用 MVC Miniprofiler,如果我注释掉“MiniProfilerEF.Initialize();”一切正常。这是 global.asax 文件的内容

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using MvcMiniProfiler;

namespace BizRadioXInternal

    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    
        public void Application_BeginRequest()
        
            if (Request.IsLocal)
            
                MiniProfiler.Start();
            
        
        public void Application_EndRequest()
        
            if (Request.IsLocal)
            
                MiniProfiler.Stop();
            
        
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        
            filters.Add(new HandleErrorAttribute());
        

        public static void RegisterRoutes(RouteCollection routes)
        
            routes.IgnoreRoute("resource.axd/*pathInfo");
            routes.MapRoute(
                "Default", // Route name
                "controller/action/id", // URL with parameters
                new  controller = "Home", action = "Index", id = UrlParameter.Optional  // Parameter defaults
            );

        
        protected void Application_Start()
        
            AreaRegistration.RegisterAllAreas();
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            MiniProfilerEF.Initialize();
        
    

【问题讨论】:

看起来您的 SQL Server CE DLL 位数有误。 实际上我正在使用 MVC Mini Profiler,如果我注释掉“MiniProfilerEF.Initialize();”,它似乎被关闭了。一切正常。我正在更新我原来的问题以反映这一点。 【参考方案1】:

这是 EF 4.1 更新 1 的问题,它破坏了所有分析器

见:

http://code.google.com/p/mvc-mini-profiler/issues/detail?id=100 http://weblogs.asp.net/fbouma/archive/2011/07/28/entity-framework-v4-1-update-1-the-kill-the-tool-eco-system-version.aspx http://ayende.com/blog/75777/entity-framework-4-1-update-1-backward-compatibility-and-microsoft

Mark Young 刚刚在主干中实现了一个特定于 SQL CE 的解决方法,使用:

// only ever set to false when profiling SQL CE
MvcMiniProfiler.Initialize_EF42(supportExplicitConnectionStrings: false); 

【讨论】:

以上是关于使用带有实体框架代码优先和 ASP.NET MVC 3 和 mvc miniprofiler 的 SQL Server CE 时出现问题的主要内容,如果未能解决你的问题,请参考以下文章

如何使用代码优先实体框架在 ASP.Net MVC3 中重新加载多对多导航属性

如何使用trackerenableddbcontext在asp.net mvc5和代码中的实体框架中实现审计跟踪

带有实体框架的 ASP.NET MVC Core 项目中的种子角色

实体框架代码优先和 ASP.NET 成员资格

实体框架探查器 - 带有 EF 6 的 ASP.NET MVC4 - 无法确定提供程序名称

带有实体框架和 SQL Server 数据库的 ASP.NET MVC - 图像未显示在视图中......错误显示“无法将“字节”转换为“字符串”