简体   繁体   中英

EF Code First “String or binary would be truncated” when running Update-Database

My Migration looks like this:

    public override void Up()
    {
        AddColumn("dbo.TargetTable", "Table1Id", c => c.Int(nullable: false));
        AddForeignKey("dbo.TargetTable", "Table1Id", "dbo.Table1", "Id");

        AddColumn("dbo.TargetTable", "Table2Id", c => c.Int(nullable: false));
        AddForeignKey("dbo.TargetTable", "Table2Id", "dbo.Table2", "Id");
    }

    public override void Down()
    {
        DropForeignKey("dbo.TargetTable", "Table1Id", "dbo.Table1", "Id");
        DropColumn("dbo.TargetTable", "Table1Id", c => c.Int(nullable: false));

        DropForeignKey("dbo.TargetTable", "Table2Id", "dbo.Table2", "Id");
        DropColumn("dbo.TargetTable", "Table2Id", c => c.Int(nullable: false));

    }

and when I run "Update-Database" I'm getting the error: String or binary data would be truncated. The statement has been terminated.

I'm not creating any tables, just adding two columns to an existing table. So I am unsure where this error could be coming from. I'm not manipulating any string or binary columns. Any help would be much appreciated.

Edit

The table is empty. It has no rows, that's why the columns are fine being non-nullable.

The Model:

 public class TargetTable
{
    //This column already exists.
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public int Table1Id { get; set; }
    public virtual Table1 Table1 { get; set; }

    public int Table2Id { get; set; }
    public virtual Table2 Table2 { get; set; }
}

You are inserting not nullable fields into existing table. If table contains rows, it will cause error.

确保列和外键上的类型相同

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM