c# - Entity Framework Code First Migration issue with linking tables -
i'm using ef 5.0 code first, using automatic migrations via pm console.
i'm attempting apply 4th migration project , convention based naming of linking tables causing them dropped , recreated different name. has not occurred during of previous migrations.
example :
i have 2 classes user , site.
initialcreate migration
this created link table called "usersites" convention.
createtable( "dbo.usersites", c => new { user_id = c.guid(nullable: false), site_id = c.guid(nullable: false), }) .primarykey(t => new { t.user_id, t.site_id }) .foreignkey("dbo.users", t => t.user_id, cascadedelete: true) .foreignkey("dbo.sites", t => t.site_id, cascadedelete: true) .index(t => t.user_id) .index(t => t.site_id);
everything works well.
skip today :
4th migration
this drops usersites link table , creates siteusers link table.
obviously not ideal!
public override void up() { dropforeignkey("dbo.usersites", "user_id", "dbo.users"); dropforeignkey("dbo.usersites", "site_id", "dbo.sites"); dropindex("dbo.usersites", new[] { "user_id" }); dropindex("dbo.usersites", new[] { "site_id" }); createtable( "dbo.siteusers", c => new { site_id = c.guid(nullable: false), user_id = c.guid(nullable: false), }) .primarykey(t => new { t.site_id, t.user_id }) .foreignkey("dbo.sites", t => t.site_id, cascadedelete: true) .foreignkey("dbo.users", t => t.user_id, cascadedelete: true) .index(t => t.site_id) .index(t => t.user_id); droptable("dbo.usersites");
i'm @ loss explain this.
neither class has changed since first implementation... , presume if apply suffer data loss.
so question(s) :
can remove code migration script , continue using existing structure?
is there gotcha don't know might have caused this?
any/all assistance appreciated!
edit:
i have defined classes below , allowed model built convention. have changed namespace of dbcontext, all! colour me bewildered.
public class user { public virtual icollection<site> sites { get; set; } } public class site { public virtual icollection<user> users { get; set; } }
it's strange situation. did change in dbcontext
? how declare sites
, users
properties in classes?
i think should explicit add many-to-many relationship db context, this:
protected override void onmodelcreating(dbmodelbuilder modelbuilder) { base.onmodelcreating(modelbuilder); modelbuilder.entity<user>() .hasmany<sites>(u => u.sites) .withmany(e => e.users) .map( m => { m.mapleftkey("user_id"); m.maprightkey("site_id"); m.totable("usersites"); }); //for prevent error 'the referential relationship result in cyclical reference not allowed' modelbuilder.entity<sites>() .hasrequired(s => s.user) .withmany() .willcascadeondelete(false); }
then remove 4th migration , try add again
if remove migration code, you'll catch navigation errors foreign keys problem, incorrect table name, etc.
Comments
Post a Comment