使用DbContext的TypeLoadException

时间:2012-06-01 12:18:58

标签: c# asp.net-mvc entity-framework

我有2个项目。第一个项目是一个dll项目,第二个是mvc4网站。 在dll中我有一个实体数据模型,我自动生成了DbContext。

在Global.asax中,我使用以下行初始化数据库:

System.Data.Entity.Database.SetInitializer( new DropCreateDatabaseAlways<WebConfigEntities>() );

当我启动网站时,我得到一个TypeLoadException

Server Error in '/' Application.
GenericArguments[0], WebConfigDB.WebConfigEntities, voor System.Data.Entity.IDatabaseInitializer`1[TContext] is in strijd met de beperking van typeparameter TContext.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.TypeLoadException: GenericArguments[0], WebConfigDB.WebConfigEntities, voor System.Data.Entity.IDatabaseInitializer`1[TContext] is in strijd met de beperking van typeparameter TContext.

Source Error:

Line 46: 
Line 47:            BundleTable.Bundles.EnableDefaultBundles();
Line 48:        }
Line 49:    }
Line 50: }


Source File: D:\projecten\MD2400\WebConfig\Global.asax.cs    Line: 48

Stack Trace:

[TypeLoadException: GenericArguments[0], WebConfigDB.WebConfigEntities, voor System.Data.Entity.IDatabaseInitializer`1[TContext] is in strijd met de beperking van typeparameter TContext.]
   WebConfig.MvcApplication.Application_Start() in D:\projecten\MD2400\WebConfig\Global.asax.cs:48

我如何解决这个问题?

3 个答案:

答案 0 :(得分:6)

此类错误通常表示不同的程序集以某种方式引用不同版本的EntityFramework.dll。确保所有项目(以及引用程序集的任何其他内容)使用完全相同的版本。此外,请确保您在GAC中没有EntityFramework.dll,或者如果您必须在GAC中拥有它,那么它也与引用的版本相同。

如果您使用的是针对不同版本构建的外部依赖项,并且您无法更改此设置,则可能需要设置绑定重定向以确保CLR能够正确解析该版本。

答案 1 :(得分:0)

异常的翻译会有所帮助。在泛型方法调用中指定Context有帮助吗?像这样:

System.Data.Entity.Database.SetInitializer<WebConfigEntities>( new DropCreateDatabaseAlways<WebConfigEntities>() );

如何将connectionString传递给WebConfigEntities类? 你可以发布它的构造函数吗?

EntityFramework可以从.config文件中检索connectionString。如果你将模型放在一个单独的dll中,那么这可能不会很好。 这并不意味着您不能将模型放在dll中,当然可以。我已经为几个项目做了这个。

答案 2 :(得分:0)

我犯了一个错误,那就是从EF dll的解决方案资源管理器获取版本号,而不是nuget软件包的版本。因此,我加载了nuget软件包版本6.0.0,而不是6.2.0。

Beware that these version are not the same thing