Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF 4.1 Code First - model updated with [Required] attributes

My model previously was without any DataNotations, but I recently changed that, applying [Required] for some properties. As this happen, my migration code start to throw an exception, like:

Unable to apply pending changes because automatic migration is disabled. To enable automatic migration, ensure that DbMigrationsConfiguration.AutomaticMigrationsEnabled is set to true.

I assume that some explicit actions of migration have to be done. Please clarify.

EDIT: AutomaticMigrationsEnabled = true is not option for me, I'm interesting how to make it possible with some migration scripts.

like image 278
Alexander Beletsky Avatar asked Feb 01 '26 06:02

Alexander Beletsky


2 Answers

Add a Configuration class extending DbMigrationsConfiguration and set the AutomaticMigrationsEnabled to true, a sample class would look like this

namespace yournamespace
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

        internal sealed class Configuration : DbMigrationsConfiguration<YourDbContext>
        {
            public Configuration()
            {
                AutomaticMigrationsEnabled = true;
                AutomaticMigrationDataLossAllowed = true;
            }


        }
    }

then add the configuration class to the DbMigrator instance as follows

namespace yournamespace
{
    public class YourDataMigrator
    {
        public void MigrateData()
        {
            DbMigrationsConfiguration configuration=new Configuration();
            DbMigrator dbMigrator = new DbMigrator(configuration);

            try
            {
                dbMigrator.Update();
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
    }

}

I think this would solve your problem

like image 53
Jayanga Avatar answered Feb 04 '26 00:02

Jayanga


You can create migration scripts through the package manager console by executing the following scripts:

PM> Enable-Migrations 

followed by

PM> Add-Migration Initial

followed by

PM>  Update-Database

Originally found here: http://www.snippetsource.net/Snippet/146/enable-automatic-migrations-in-ef-codefirst-c

like image 21
Christian Moser Avatar answered Feb 03 '26 23:02

Christian Moser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!