将 SQL Server CE 与实体框架代码优先以及 ASP.NET MVC 3 和 mvc miniprofiler 结合使用时出现问题

发布于 2024-12-07 04:53:55 字数 7137 浏览 0 评论 0原文

我正在尝试使用 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();
        }
    }
}

I am attempting to create an ASP.NET MVC 3 application using C#, Entity Framework 4.0 code-first and SQL Server CE, and the automated scaffolding. Everything works fine until I try to actually use a page that connects to the SQL Server CE database.

My connection in the web.config is this

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

My model class looks like this

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; }
    }
}

and my data context class looks like this

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; }
    }
}

and every time I try go to a page that touches the database (like a standard index page) I get the following error

The given assembly name or codebase was invalid. (Exception from
HRESULT: 0x80131047)

Here is the stack trace

[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

What on earth am I doing wrong?

Update: The root cause of the problem seems to be in the global.asax file. I'm using the MVC Miniprofiler, and if I comment out "MiniProfilerEF.Initialize();" everything works fine. Here is the contents of the global.asax file

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();
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

白衬杉格子梦 2024-12-14 04:53:55

这是 EF 4.1 update 1 的问题,它会破坏所有分析器

请参阅:

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

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

This is an issue with EF 4.1 update 1 which breaks all profilers

See:

Mark Young just implemented a SQL CE specific workaround in the main trunk, use:

// only ever set to false when profiling SQL CE
MvcMiniProfiler.Initialize_EF42(supportExplicitConnectionStrings: false); 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文