【发布时间】:2019-06-02 20:00:14
【问题描述】:
我正在尝试运行迁移。迁移完成,但是,当我尝试更新数据库时,我收到此错误消息
无法将值 NULL 插入到列“scheduleDateAndTimeid”、表“aspnet-ScheduleWebApp-20190525082521.dbo.Students”中;列不允许空值。更新失败。
我有两个模型类,一个叫student,另一个叫scheduleDateAndTime。
我在student 模型上创建了一个带有映射的DTO,并向scheduleDateAndTime 添加了一个导航属性
迁移
public partial class AnotherMigrationTwoTWOTwotwo : DbMigration
{
public override void Up()
{
DropForeignKey("dbo.Students", "scheduleDateAndTime_id", "dbo.ScheduleDateAndTimes");
DropIndex("dbo.Students", new[] { "scheduleDateAndTime_id" });
RenameColumn(table: "dbo.Students", name: "scheduleDateAndTime_id", newName: "scheduleDateAndTimeid");
AlterColumn("dbo.Students", "scheduleDateAndTimeid", c => c.Int(nullable: false));
CreateIndex("dbo.Students", "scheduleDateAndTimeid");
AddForeignKey("dbo.Students", "scheduleDateAndTimeid", "dbo.ScheduleDateAndTimes", "id", cascadeDelete: true);
}
public override void Down()
{
DropForeignKey("dbo.Students", "scheduleDateAndTimeid", "dbo.ScheduleDateAndTimes");
DropIndex("dbo.Students", new[] { "scheduleDateAndTimeid" });
AlterColumn("dbo.Students", "scheduleDateAndTimeid", c => c.Int());
RenameColumn(table: "dbo.Students", name: "scheduleDateAndTimeid", newName: "scheduleDateAndTime_id");
CreateIndex("dbo.Students", "scheduleDateAndTime_id");
AddForeignKey("dbo.Students", "scheduleDateAndTime_id", "dbo.ScheduleDateAndTimes", "id");
}
}
StudentDto模型类:
public class StudentDto
{
public int id { get; set; }
public string name { get; set; }
public byte age { get; set; }
public string subjectStudying { get; set; }
public string disability { get; set; }
public string additionalInformation { get; set; }
public ScheduleDateAndTimeDto ScheduleDateAndTime { get; set; }
public int scheduleDateAndTimeid { get; set; }
}
【问题讨论】:
-
可能您在要重命名并设置为 nullable = false 的列中有一些空值
-
这是迁移的问题之一,很难添加新的非空列。如果需要
Student.ScheduleDateAndTime,则必须在添加(或启用)FK 约束之前创建ScheduleDateAndTime记录。
标签: c# asp.net entity-framework