c# - Switching to artificial key with different type in Entity Framework Migrations -


i'm working on entity framework code first project where, previously, had class field called "id" string type , using hash.

that's specified this:

[key] public string id { get; set; } 

that's no longer need because updates can have duplicate values, want change this:

[databasegenerated(databasegeneratedoption.identity)] public int id { get; set; }  [required] [index] public string hash { get; set; } //this represents used id 

i ran trouble , went digging , found a bug report suggesting work in entity framework 6.1.0, i've updated, it's still not working me. hand-entered sql migration file set hash column id value before gets blown away, update fails when goes update foreign keys because can't figure out how go alphanumeric nvarchar int. of course, i'd insert integer id corresponds old hash.

is there nondestructive way can achieve this?

well, little bit hesitant post solution ended going with, because feels bit of hack, since don't expect other answers @ point, here is.

i ended hand-editing migration method. essentially, i'm dropping constraints, doing update query nvarchar representation of integer key, converting int , adding constraints again.

public override void up()   {     dropindex("dbo.valuesetelements", new[] { "parent_id" });     dropindex("dbo.sectionelements", new[] { "choices_id" });     dropforeignkey("dbo.valuesetelements", "parent_id", "dbo.valuesets");     dropforeignkey("dbo.sectionelements", "choices_id", "dbo.valuesets");     dropprimarykey(valuesettable, "pk_dbo.valuesets");     renamecolumn(valuesettable, "id", "hash");     addcolumn(valuesettable, "id", c => c.int(nullable: false, identity: true, name: "id"));     addprimarykey(valuesettable, "id");     createindex(valuesettable, "hash");     sql("update dbo.sectionelements set choices_id = convert(nvarchar(10), (select id dbo.valuesets dbo.valuesets.hash = dbo.sectionelements.choices_id))");     altercolumn("dbo.sectionelements", "choices_id", c => c.int());     addforeignkey("dbo.sectionelements", "choices_id", "dbo.valuesets", "id");     createindex("dbo.sectionelements", "choices_id");     sql("alter table dbo.valuesetelements drop constraint [df__valuesete__paren__0f63164f]");     sql("update dbo.valuesetelements set parent_id = convert(nvarchar(10), (select id dbo.valuesets dbo.valuesets.hash = dbo.valuesetelements.parent_id))");     altercolumn("dbo.valuesetelements", "parent_id", c => c.int(nullable: false));     addforeignkey("dbo.valuesetelements", "parent_id", valuesettable, "id", cascadedelete: true);     createindex("dbo.valuesetelements", "parent_id");   } 

Comments

Popular posts from this blog

jQuery Mobile app not scrolling in Firefox -

c++ - How to add Crypto++ library to Qt project -

how to receive file in java(servlet/jsp) -