adding a foreign key with Code First migration

前端 未结 6 1822
花落未央
花落未央 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 03:08

    This is an old issue but currently there is no need to create a separate migration and this issue can be solved using a few steps:

    1. Run Add-Migration with the entity changes (a new non-nullable reference property added, ProductId in this case) to scaffold a new migration class
    2. Modify newly added migration to create a nullable column (nullable: true) instead of non-nullable
    3. Below AddColumn add Sql command setting the value of the column as needed
    4. Below add AlterColumn command which will make the column non-nullable as intended

    In the example above this would look like:

        public override void Up()
        {
            AddColumn("dbo.ProductFeatures", "ProductId", c => c.Int(nullable: true));
            Sql("UPDATE [dbo].[ProductFeatures] SET ProductId = (SELECT TOP 1 [Id] FROM [dbo].[Products])");
            AlterColumn("dbo.ProductFeatures", "ProductId", c => c.Int(nullable: false));
            CreateIndex("dbo.ProductFeatures", "ProductId");
            AddForeignKey("dbo.ProductFeatures", "ProductId", "dbo.Products", "Id");
        }
    

提交回复
热议问题