EF 5 Code First Migration Bulk SQL Data Seeding

戏子无情 提交于 2019-11-28 23:16:51

问题


I am using EF5 with MVC4. The problem is that I have large data in my DB which I already imported from legacy DB. I want to load seed that data when model changes. My question is how can I seed large amount of data that is already in my DB?

internal sealed class Configuration : MigrationsConfiguration<VoiceLab.Models.EFDataContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
    }

    protected override void Seed(VoiceLab.Models.EFDataContext context)
    {
     //what to do here to seed thousands or records that are already in db
    }

}

thanks,


回答1:


Here is how you can seed bulk data by just providing the .sql files in seed method.

public class AppContextInitializer : CreateDatabaseIfNotExists<AppContext>
{
    protected override void Seed(AppContext context)
    {
        var sqlFiles = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.sql").OrderBy(x => x);
        foreach (string file in sqlFiles)
        {
            context.Database.ExecuteSqlCommand(File.ReadAllText(file));
        }

        base.Seed(context);
    }
}



回答2:


Code-based migration is the recommended approach for existing databases (manual database update) after model changes. You can do it form PowerShell in Package Comand Line windows. In that way existing data will be preserved.

If you are part of a team of developers that use source control you should either use purely automatic migrations or purely code-based migrations. Given the limitations of automatic migrations using code-based migrations in team environments is recommend.

http://msdn.microsoft.com/en-us/data/jj591621

http://elegantcode.com/2012/04/12/entity-framework-migrations-tips/

internal sealed class Configuration : MigrationsConfiguration<DataContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;

        // if model changes involve data lose
        AutomaticMigrationDataLossAllowed = true;

    }

    protected override void Seed(DataContext context)
    {
     //seed only when creating or new database
    }

}


来源:https://stackoverflow.com/questions/12904692/ef-5-code-first-migration-bulk-sql-data-seeding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!