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

时间:2019-06-02 20:00:14

标签: c# asp.net entity-framework

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

  

无法将值NULL插入表'aspnet-ScheduleWebApp-20190525082521.dbo.Students'的列'scheduleDateAndTimeid'中;列不允许为空。 UPDATE失败。

我有两个模型类,一个叫做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; }
}

3 个答案:

答案 0 :(得分:0)

该列中有一个null值。在迁移之前,请对这些Sql("UPDATE t SET c = 1 WHERE c IS NULL")值进行某种更新(例如,null

答案 1 :(得分:0)

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

这听起来像是一个限制,但绝对有道理:如果您将列更新为不可空,那么迁移应如何处理现有数据? (考虑生产环境版本等。)

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

答案 2 :(得分:0)

执行正确的操作并使数据规范化,而不是破坏数据库以插入无效数据或破坏引用完整性。

CREATE TABLE StudentSchedule (
    studentID INT FOREIGN KEY Students.id,
    scheduleID INT FOREIGN KEY ScheduleDateAndTimes.id
)

删除Students.scheduleDateAndTime_id。收到Students.scheduleDateAndTime_id后,请在StudentSchedule中插入一行。如果一个学生只能有一个scheduleDateAndTimeid,则使StudentSchedule.studentID唯一。

相关问题