C# 实体框架代码优先迁移的例外情况
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9582129/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Exceptions for Entity Framework Code First Migrations
提问by Alexander van Trijffel
I'm getting several unhandled exceptions while using Code First Migrations of Entity Framework 4.3.
在使用实体框架 4.3 的代码优先迁移时,我遇到了几个未处理的异常。
The database context:
数据库上下文:
public class MyAppContext : DbContext
{
public DbSet<Branch> Branches { get; set; }
public MyAppContext()
{ }
}
The entity:
实体:
public class Branch : IEntity<Guid>
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool Active { get; set; }
}
The database initializer:
数据库初始化程序:
public class MyAppInitializer : CreateDatabaseIfNotExists<MyAppContext>
{
protected override void Seed(MyAppContext context)
{
context.Branches.Add(new Branch() { Id = branchId, Name = "Acme", Description = "Acme", Active = true });
context.SaveChanges();
}
}
I installed Entity Framework 4.3 to my DAL project and MVC project using:
我使用以下命令将 Entity Framework 4.3 安装到我的 DAL 项目和 MVC 项目:
Install-Package EntityFramework
安装包实体框架
I have set the MVC project as the startup project and executed the following command to the DAL project with the database context and initializer:
我已将 MVC 项目设置为启动项目,并使用数据库上下文和初始化程序对 DAL 项目执行以下命令:
PM> Enable-Migrations -Verbose
Using NuGet project 'Ckms.KeyManagement.Managers'. Error while searching for context type (specify -Verbose to see exception details). System.Data.Entity.Migrations.Design.ToolingException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner) at System.Data.Entity.Migrations.Design.ToolingFacade.GetContextTypes()
at System.Data.Entity.Migrations.MigrationsCommands.FindContextToEnable() Edit the generated Configuration class to specify the context to enable migrations for. Code First Migrations enabled for project Ckms.KeyManagement.Managers.
PM> Enable-Migrations -Verbose
使用 NuGet 项目“Ckms.KeyManagement.Managers”。搜索上下文类型时出错(指定 -Verbose 以查看异常详细信息)。System.Data.Entity.Migrations.Design.ToolingException:无法加载一种或多种请求的类型。检索 LoaderExceptions 属性以获取更多信息。在 System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner) 在 System.Data.Entity.Migrations.Design.ToolingFacade.GetContextTypes()
在 System.Data.Entity.Migrations.MigrationsCommands.FindContextToEnable() 编辑生成的配置类来指定启用迁移的上下文。为项目 Ckms.KeyManagement.Managers 启用代码优先迁移。
A DbMigrationsConfiguration child class is added to the DAL project. If I add the type of the DbContext manually and enable Automatic Migrations:
将 DbMigrationsConfiguration 子类添加到 DAL 项目。如果我手动添加 DbContext 的类型并启用自动迁移:
internal sealed class Configuration : DbMigrationsConfiguration<MyAppContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(MyAppContext context)
{ }
}
These exceptions are thrown for the Add-Migration and Update-Database commands:
Add-Migration 和 Update-Database 命令会抛出这些异常:
PM> Add-Migration TestEFMigrationsColumn -Verbose
Using NuGet project 'Ckms.KeyManagement.Managers'. Using StartUp project ''. System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentException: The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG)) --- End of inner exception stack trace --- at System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32 culture, String[] namedParameters) at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams) at System.Management.Automation.ComMethod.InvokeMethod(PSMethod method, Object[] arguments) Exception has been thrown by the target of an invocation.
PM> 添加-迁移测试EFMigrationsColumn -Verbose
使用 NuGet 项目“Ckms.KeyManagement.Managers”。使用启动项目''。System.Reflection.TargetInvocationException:调用的目标已抛出异常。---> System.ArgumentException: 参数不正确。(来自 HRESULT 的异常:0x80070057(E_INVALIDARG))---内部异常堆栈跟踪结束---在 System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32culture , String[] namedParameters) 在 System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfoculture, String[] namedParams) 在 System.Management.Automation。 ComMethod.InvokeMethod(PSMethod 方法,
Update-Database:
更新数据库:
PM> Update-Database -Verbose
Using NuGet project 'Ckms.KeyManagement.Managers'. Using StartUp project ''. System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentException: The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG)) --- End of inner exception stack trace --- at System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32 culture, String[] namedParameters) at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams) at System.Management.Automation.ComMethod.InvokeMethod(PSMethod method, Object[] arguments) Exception has been thrown by the target of an invocation.
PM> 更新-数据库-详细
使用 NuGet 项目“Ckms.KeyManagement.Managers”。使用启动项目''。System.Reflection.TargetInvocationException:调用的目标已抛出异常。---> System.ArgumentException: 参数不正确。(来自 HRESULT 的异常:0x80070057(E_INVALIDARG))---内部异常堆栈跟踪结束---在 System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32culture , String[] namedParameters) 在 System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfoculture, String[] namedParams) 在 System.Management.Automation。 ComMethod.InvokeMethod(PSMethod 方法,
Any ideas? The error messages are not really helpful. I have tried the Nuget commands with and without an existing database.
有任何想法吗?错误消息并没有真正的帮助。我已经尝试过使用和不使用现有数据库的 Nuget 命令。
采纳答案by Marcin
If you are using separate library for data access you need to provide it name when running query:
如果您使用单独的库进行数据访问,则需要在运行查询时提供它的名称:
Add-Migration -StartUpProjectName "Your DAL Project" MyNewMigration
Add-Migration -StartUpProjectName "Your DAL Project" MyNewMigration
Update-Database -StartUpProjectName "Your DAL Project" -Verbose
Update-Database -StartUpProjectName "Your DAL Project" -Verbose
回答by Ujjwal
add-migration -Name First -ProjectName DbSet.Framework -StartUpProjectName CodeFirstConsole
First: Name of Migration
第一:迁移名称
Dbset.Framework: Project where dbContext and other classes
dbset.Framework:dbContext 和其他类所在的项目
CodeFirstConsole: Start Up project (could be your web, windows or console app)
CodeFirstConsole:启动项目(可以是您的 Web、Windows 或控制台应用程序)
回答by Paul
For System.ArgumentException: The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG)) adding -projectname and startupprojectname did not help.
对于 System.ArgumentException:参数不正确。(来自 HRESULT 的异常:0x80070057 (E_INVALIDARG))添加 -projectname 和 startupprojectname 没有帮助。
Setting the PackageManager Console's "Default Project" Dropdown to point to the Library (in my case) where I wanted the "Migration folder" and its expected contents to be was the only way to get this running from a multiproject solution.
将 PackageManager 控制台的“默认项目”下拉列表设置为指向我希望“迁移文件夹”及其预期内容所在的库(在我的情况下)是从多项目解决方案中运行它的唯一方法。
回答by Nidhin
I also had the same issue. Found out that if anything is wrong with the config files this error comes up. I had duplicate tags in web.config and removing these solved my issue.
我也有同样的问题。发现如果配置文件有任何问题,就会出现此错误。我在 web.config 中有重复的标签,删除这些标签解决了我的问题。
回答by Thorarins
Ran into the same problem , solved by removing <globalization>from web.config.
遇到了同样的问题,通过<globalization>从 web.config 中删除来解决。
回答by Yasir Ali
I had solve this problem only by changing the nameused in connection string.
我只能通过更改连接字符串中使用的名称来解决这个问题。
<add name="abcd" providerName="System.Data.SqlClient" connectionString="Data Source=.\SQLEXPRESS;AttachDbFileName=|DataDirectory|\DatabaseFileName.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True" />
And I use connectionStrings after closing tag of the
我在关闭标签后使用 connectionStrings
appSettings
and just before starting tag of
就在开始标记之前
system.web
Make sure that namethat you use in connectionStringnot used in other connections.
确保您使用的名称connectionString未在其他连接中使用。
回答by Eagle D Ikechukwu
You must be having two connection strings in your web. Config files. Just delete one
您的网络中必须有两个连接字符串。配置文件。删一个就行

