c# – 代码优先迁移 – 实体框架 – 无法向列中添加列
这个问题已经被多次以不同的口味询问了.我经历了所有的答案,烧了很多时间.我似乎不能得到这个工作.
我一直在使用asp.net mvc实体框架,SQL Server应用程序.我已经有一个现有的数据库,表等,每件事情都在工作.我只需要在表中添加一个新的列. 所以..我在模型类中添加了一个属性,所以我可以将列添加到表中.但没有成功. 所以我按照以下顺序执行步骤. >在我的模型类中添加该字段. [Required] public string EmailSubject{ get; set; } >然后我删除我的asp.net mvc项目中包含Configuration.cs类的文件夹Migrations Enable-Migrations -ContextTypeName AppointmentReminder.Data.ReminderDb -Force >然后我将属性设置为true,如下所示 public Configuration() { AutomaticMigrationsEnabled = true; } >然后我在包管理器控制台中发出以下命令. Update-Database -Verbose -Force 这是我的连接字符串到数据库的默认连接 Data Source=(LocalDb)v11.0;AttachDbFilename=C:practiceAppointmentReminder4AppointmentReminder4App_Dataaspnet-AppointmentReminder4-20141202060615.mdf;Initial Catalog=aspnet-AppointmentReminder4-20141202060615;Integrated Security=True 但是我无法在我所需的表格中添加新的列. 编辑1 我更新了模型如下,没有必要的属性,并执行了上述所有步骤,但我仍然无法将列添加到表中. public string EmailBody { get; set; } 以下是所有命令及其输出. PM> Enable-Migrations -ContextTypeName AppointmentReminder.Data.ReminderDb -Force Checking if the context targets an existing database... Code First Migrations enabled for project AppointmentReminder4. PM> Update-Database -Verbose -Force Using StartUp project 'AppointmentReminder4'. Using NuGet project 'AppointmentReminder4'. Specify the '-Verbose' flag to view the SQL statements being applied to the target database. Target database is: 'aspnet-AppointmentReminder4-20141202060615' (DataSource: (LocalDb)v11.0,Provider: System.Data.SqlClient,Origin: Configuration). No pending explicit migrations. Running Seed method. PM> Update-Database -Verbose -Force Using StartUp project 'AppointmentReminder4'. Using NuGet project 'AppointmentReminder4'. Specify the '-Verbose' flag to view the SQL statements being applied to the target database. Target database is: 'aspnet-AppointmentReminder4-20141202060615' (DataSource: (LocalDb)v11.0,Origin: Configuration). No pending explicit migrations. Running Seed method. PM> 编辑2 解决方法
因为该字段是必需的,您需要指定默认值.编辑您的迁移文件,找到添加列的行,并指定默认值应为:
public override void Up() { AddColumn("dbo.MyTable","EmailSubject",c => c.String(nullable: false,defaultValue: "")); } 以供参考: 编辑:根据您的编辑,您需要在尝试更新之前创建迁移.请参阅this example了解您通常如何使用它. 但是,如果您尝试将代码优先迁移应用于现有数据库,本文可能会有所帮助:Code First Migrations with an existing database (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |