Yitzhak Weinberg
Yitzhak Weinberg

Reputation: 2582

seed data from one database to other database when application start to run mvc

i have to database one is realy database and second database to testing i need the realy data for testing i want always the solution is run to copy the real data to the testing database using mvc c# i think i need code like this

protected void Application_Start()
{
    Database.SetInitializer<LocatorContext>(new DropCreateDatabaseAlways<LocatorContext>());

    AreaRegistration.RegisterAllAreas();
    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
}

Upvotes: 1

Views: 807

Answers (1)

Bassam Alugili
Bassam Alugili

Reputation: 17043

To seed data into your database, you have to create custom database initializer,and override the Seed method.

The following example shows how you can provide default data from another database or another SQL server.

You can also use context.Database.SqlQuery to handle/update the data in C# Seed method and then push the changes back to the Sql Server/database.

public class SeedDbInitializer : DropCreateDatabaseAlways<MyDbContext>
 {
     protected override void Seed(MyDbContext context)
     {
        context.Database.ExecuteSqlCommand(
                                           @"SELECT * INTO targetTable
                                            FROM[sourceserver].[sourcedatabase].[dbo].[sourceTable]"
                                           );
        base.Seed(context);
     }
  }

public class MyDbContext : DbContext
 {
     public MyDbContext() : base("MyConnectionString")
     {
       Database.SetInitializer<MyDbContext>(new SeedDbInitializer());
     }
    public DbSet<User> Users { get; set; }
 }

Upvotes: 2

Related Questions