c# - Entity Framework migration insert default value from function -


i using entity framework 6.1.1 code-first.

i trying add new property object (with migration , existing db values) unique

this object:

public class {     public int id { get; set; }     public string name { get; set; } } 

and after edit:

public class {     public int id { get; set; }     public string name { get; set; }     public string newuniquevalue { get; set; } } 

and fluent api:

modelbuilder.entity<a>().haskey(x => x.id); modelbuilder.entity<a>().property(x => x.id).hasdatabasegeneratedoption(databasegeneratedoption.identity);  // after added new property modelbuilder.entity<a>().property(x => x.newuniquevalue).hasmaxlength(20).hascolumnannotation("index", new indexannotation(new indexattribute() { isunique = true })); 

but when try run update-database, error

duplicate key value (null)

(obviously...)

so question is: there way call function (from code) generate such key?

to call function generation:

public static string generate() {     random rnd = new random();      var chars = "abcdef0123456789";     var unique = string.empty;      (int = 0; < 20; i++)     {         unique += chars[rnd.next(0, chars.length)];     }      return unique; } 

you should fill empty newuniquevalue cells @ migration section:

public override void up() {     addcolumn("dbo.tablea", "newuniquevalue", c => c.string(maxlength: 20));     //you should add row:     sql("update dbo.tablea set newuniquevalue = newid()")     createindex("dbo.tablea", "newuniquevalue", unique: true); }  public override void down() {     dropindex("dbo.tablea", "newuniquevalue");     dropcolumn("dbo.tablea", "newuniquevalue"); } 

Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -