EF 6 Code-Based Migration: Add not null property to existing entity

╄→гoц情女王★ 提交于 2019-12-24 00:19:28

问题


I want to add a not-null, foreing key column to an existing table.

Environment: EF 6,Code-First, Code-Based Migration

//Code from Migration class for new entity Currency
CreateTable("dbo.Currency",
                c => new
                    {
                        CurrencyID = c.Int(nullable: false, identity: true),
                        Code = c.String(nullable: false, maxLength: 3, fixedLength: true, unicode: false),
                        Denomination = c.String(nullable: false, maxLength: 50, unicode: false),
                    })
                .PrimaryKey(t => t.CurrencyID);

AddColumn("dbo.Collection", "CurrencyID", c => c.Int(nullable: false));

//Code from Seed() method in Configuration class 
context.Currencies.AddOrUpdate(
    new Currency
    {
        Code = "USD",
        Denomination = "Dollar"
    }
);

//Here i get an exception. Collection is the existing table
context.Database.ExecuteSqlCommand( "update collection set CurrencyID = 1 ); 

Exception message:

The UPDATE statement conflicted with the FOREIGN KEY constraint "FK_dbo.Collection_dbo.Currency_CurrencyID". The conflict occurred in table "dbo.Currency", column 'CurrencyID'.


回答1:


Problem solved, here are enumerated by order the steps i followed:

  1. Change the foreign key property mapping to Not Required
  2. Seed only the primary key values
  3. Update-Database
  4. Change back the property to Required
  5. Add new migration and seed the values for foreign key column
  6. Update-Database


来源:https://stackoverflow.com/questions/22665416/ef-6-code-based-migration-add-not-null-property-to-existing-entity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!