将模型属性转换/迁移到导航属性的步骤是什么(使用EF Code First Migration创建新类并创建外键关系。
在下面的示例中,我想将Student类属性Country转换为导航属性,而不会丢失数据。
当前模式
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public string Country { get; set; }
}
建议模型
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public int CountryID { get; set; }
public virtual Country Country { get; set; }
}
public class Country
{
public int ID { get; set; }
public string Country { get; set; }
}
添加迁移NavigationProperty
public override void Up()
{
CreateTable(
"dbo.Countries",
c => new
{
ID = c.Int(nullable: false, identity: true),
CountryName = c.String(),
})
.PrimaryKey(t => t.ID);
AddColumn("dbo.Students", "CountryID", c => c.Int(nullable: false));
CreateIndex("dbo.Students", "CountryID");
AddForeignKey("dbo.Students", "CountryID", "dbo.Countries", "ID", cascadeDelete: true);
DropColumn("dbo.Students", "Country");
}
更新 - 数据库错误
System.Data.SqlClient.SqlException(0x80131904):ALTER TABLE语句与FOREIGN KEY约束冲突" FK_dbo.Students_dbo.Countries_CountryID"。冲突发生在数据库" aspnet-navprop-20141009041805",table" dbo.Countries",column' ID'。