【问题标题】:EF 4.1 RC - 'System.Data.Entity.IDatabaseInitializer`1[TContext]' violates the constraint of type parameter 'TContext'EF 4.1 RC -“System.Data.Entity.IDatabaseInitializer`1[TContext]”违反了类型参数“TContext”的约束
【发布时间】:2011-03-24 23:11:53
【问题描述】:

我刚刚将我的项目(使用 NuGet)更新到 Entity Framework 4.1 RC 并收到此错误消息:

通用参数[0], 'Notesnhac.Library.NotesnhacContext', 在 'System.Data.Entity.IDatabaseInitializer`1[TContext]' 违反类型的约束 参数“TContext”。

描述:未处理的异常 在执行过程中发生 当前的网络请求。请查看 堆栈跟踪以获取有关的更多信息 错误及其起源 编码。

异常详情: System.TypeLoadException: 通用参数[0], 'Notesnhac.Library.NotesnhacContext', 在 'System.Data.Entity.IDatabaseInitializer`1[TContext]' 违反类型的约束 参数“TContext”。

来源错误:

线 114:DependencyResolver.SetResolver(新 StructureMapDependencyResolver(容器)); 第 115 行:#endregion 第 116 行:} 第 117 行:} 第 118 行:}

源文件:C:\projects\Kenny 项目\Notesnhac\Notesnhac.Site\Global.asax.cs 线路:116

堆栈跟踪:

[类型加载异常: 通用参数[0], 'Notesnhac.Library.NotesnhacContext', 在 'System.Data.Entity.IDatabaseInitializer`1[TContext]' 违反类型的约束 参数“TContext”。]
Notesnhac.Site.MvcApplication.Application_Start() 在 C:\projects\肯尼 项目\Notesnhac\Notesnhac.Site\Global.asax.cs:116

版本信息:Microsoft .NET 框架版本:4.0.30319; ASP.NET 版本:4.0.30319.225

它说错误在第 116 行,但我认为这不是错误所在。这是一段显示错误的代码片段,第 116 行是#endregion 之后的花括号:

protected void Application_Start()
{
    // Initalizes the database
    System.Data.Entity.Database.SetInitializer<NotesnhacContext>(new ContextInitializer());

    AreaRegistration.RegisterAllAreas();
    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

    AutoMapperConfig.CreateMappings();

    ControllerBuilder.Current.DefaultNamespaces.Add("Notesnhac.Site.Controllers");

    #region StructureMap IoC
    IContainer container = new Container(x =>
    {
        x.For<IControllerActivator>().Use<StructureMapControllerActivator>();
        x.Scan(s =>
        {
            s.Assembly("Notesnhac.Library");
            s.TheCallingAssembly();
            s.AddAllTypesOf<IController>().NameBy(type => type.Name.Replace("Controller", "").ToLower());
            s.WithDefaultConventions();
        });
    });
    DependencyResolver.SetResolver(new StructureMapDependencyResolver(container));
    #endregion
}

谢谢。

【问题讨论】:

    标签: asp.net-mvc entity-framework asp.net-mvc-3 entity-framework-4


    【解决方案1】:

    问题似乎出在这条线上:

    System.Data.Entity.Database.SetInitializer<NotesnhacContext>(new ContextInitializer());
    

    通用参数TContextrequired to be a DbContext subtype。而且你的策略必须实现 IDatabaseInitializer。

    您没有显示NotesnhacContext 的声明,但编译器说缺少其中之一。

    您根本不需要指定类型参数;它将从论点中推断出来。你可以这样做:

    System.Data.Entity.Database.SetInitializer(new ContextInitializer());
    

    ...假设您首先解决了声明的问题。

    【讨论】:

    • 啊,我不知道此版本中的 API 发生了一些变化 :) 感谢 Craig 指出这一点。
    猜你喜欢
    • 1970-01-01
    • 2019-06-13
    • 2018-10-04
    • 1970-01-01
    • 2018-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多