Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF 5 Code First Migration Bulk SQL Data Seeding

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,

like image 687
Tepu Avatar asked Oct 15 '12 22:10

Tepu


People also ask

Which method can be used to seed initial data in database using Entity Framework Core?

Seed Data in Entity Framework Core So as soon as we execute our migration files to create and configure the database, we want to populate it with some initial data. This action is called Data Seeding. So, we are using the HasData method to inform EF Core about the data it has to seed.

How do I code my first migration to an existing database?

Run the Add-Migration InitialCreate command in Package Manager Console. This creates a migration to create the existing schema. Comment out all code in the Up method of the newly created migration. This will allow us to 'apply' the migration to the local database without trying to recreate all the tables etc.


1 Answers

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);
    }
}
like image 197
Tepu Avatar answered Sep 21 '22 03:09

Tepu