adding a foreign key with Code First migration

前端 未结 6 1821
花落未央
花落未央 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:55

    I'm not sure if this topic is still actual, but at least with EF 6 you can do the following to assign default value into a new foreign key.

    This is how EF create a new foreign key by default:

                AddColumn("dbo.Table", "AnotherTableId", c => .Int(nullable: false));
                CreateIndex("dbo.Table", "AnotherTableId");
                AddForeignKey("dbo.Table", "AnotherTableId", "dbo.AnotherTable", "Id");
    

    Just change it as below

                AddColumn("dbo.Table", "AnotherTableId", c => 
                { 
                    var model = c.Int(nullable: false);
                    model.DefaultValue = 1;
                    return model; 
                });
                CreateIndex("dbo.Table", "AnotherTableId");
                AddForeignKey("dbo.Table", "AnotherTableId", "dbo.AnotherTable", "Id");
    

提交回复
热议问题