ef code first - Entity Framework Migrations: Prevent dropping column or table -
if ef migration
decides rename column
(or table
), fulfills dropping (old) column , adding column new name. leads data loss.
is there way prevent ef migration
dropping column , force use renamecolumn
instead?
well, didn't find clear , straightforward solution.
my solution hiding dbmigration
class every migration generated using code-based migration derived from. introducing new class same name (dbmigration
). put inside same assembly , same namespace code files reside. way, reference of code files original dbmigration
goes fake dbmigration
. then, can prevent dropping column or allow through explicit request:
namespace myproject.dal.migrations { /// <summary> /// customized dbmigration protect columns dropped accidentally /// </summary> public abstract class dbmigration : global::system.data.entity.migrations.dbmigration { public bool allodropcolumn { get; set; } protected internal new void dropcolumn(string table, string name, object anonymousarguments = null) { if (!allodropcolumn) throw new exception("myproject: dropping column while updating database prohibited. if want drop column(s), set property 'allowdropcolumn' true."); } } }
and in code file:
public partial class _1 : dbmigration { public override void up() { allodropcolumn = true; // allow column drop addcolumn("driver.truckdriver", "fullname2", c => c.string()); dropcolumn("driver.truckdriver", "fullname"); } public override void down() { addcolumn("driver.truckdriver", "fullname", c => c.string()); dropcolumn("driver.truckdriver", "fullname2"); } }
Comments
Post a Comment