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; }
}
答案 0 :(得分:0)
You are inserting not nullable fields into existing table. If table contains rows, it will cause error.
答案 1 :(得分:0)
Make sure the types on the column and foreign key are the same type