无法将 NULL 值插入列错误消息

Gol*_*avo 1 c# asp.net entity-framework

我正在尝试进行迁移。迁移完成,但是,当我尝试更新数据库时,我收到此错误消息

无法将 NULL 值插入表“aspnet-ScheduleWebApp-20190525082521.dbo.Students”列“scheduleDateAndTimeid”;列不允许为空。更新失败。

我有两个模型类,一个称为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");
    }
}
Run Code Online (Sandbox Code Playgroud)

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; }
}
Run Code Online (Sandbox Code Playgroud)

n0i*_*dea 6

您正在尝试通过将可为空的外键设置为不可为空的外键来更新表:如果您使用空表(无记录)进行操作,则此操作将正常工作,但如果存在现有记录,则迁移可能会失败在该列的这些记录中遇到 NULL 值(这是迁移之前的有效值)

\n\n

这听起来像是一个限制,但绝对有意义:如果您\xe2\x80\x99将列更新为不可为空,则迁移应如何处理现有数据? (考虑生产环境发布等......)

\n\n

解决方法可能是首先保持列可为空,然后更新现有记录的所有 NULL 值,然后使其不可为空。

\n