asp.net - EF5 Code-First - Create new table -
i'm working asp.net mvc3 & entity framework5.
my database has been designed code-first.
entity code
public class user { public int id { get; set; } public string name { get; set; } } public class efdbcontext : dbcontext { public dbset<user> users { get; set; } }
create db option
database.setinitializer(new dropcreatedatabaseifmodelchanges<efdbcontext>());
i use option, database has been created.
after database has been created, need role table was.
so had modify code follows.
entity code
public class user { public int id { get; set; } public string name { get; set; } } public class role { public int id { get; set; } public string name { get; set; } } public class efdbcontext : dbcontext { public dbset<user> users { get; set; } public dbset<role> roles { get; set; } }
i use create db option again.
in case, existing users table deleted after regeneration.
i added role table, leave data in table users.
what should do?
use code-first migrations.
database.setinitializer(null);
then in package manager console
write:
add-migration addedroles
if did't enabled migrations before, must enable first:
enable-migrations
and last:
update-database
complete guid: http://msdn.microsoft.com/en-us/data/jj591621
edit
if want database upgraded automatically whenever run application, can use migratedatabasetolatestversion
initializer:
database.setinitializer(new migratedatabasetolatestversion<efdbcontext, configuration>());
Comments
Post a Comment