adding a foreign key with Code First migration

前端 未结 6 1809
花落未央
花落未央 2020-12-24 02:15

I have an error when trying to update my database after adding a migration.

Here are my classes before add-migration

public class Product
{
    publi         


        
6条回答
  •  臣服心动
    2020-12-24 02:51

    I came across this problem today. Here's how I handled it. I did have to make my FK property nullable which was not a big deal in my case.

    I made my changes to my POCO, generated the migration and then added the following to the migration.

    public partial class LineItemProductionHistory_v4 : DbMigration
    {
        public override void Up()
        {
            AddColumn("LineItemProductionHistories","TempLineItemId",c=>c.Int());
            Sql("Update LineItemProductionHistories Set TempLineItemId = LineItem_Id");
           .
           . Generated code
           .
            Sql("Update LineItemProductionHistories Set LineItemId = TempLineItemId");
            DropColumn("LineItemProductionHistories", "TempLineItemId");
        }
    }
    

    I'm just temporarily storing all off the foreign keys, letting the migration do it's add/drop stuff and then putting the foreign keys back in the newly created FK.

提交回复
热议问题