Smaug
Smaug

Reputation: 2673

How to easily convert .sdf developed in Vs 2010 to SQL Server database

I don't have SQL Server installed my machine. Hence I decided to start working with a SQL Server Compact Edition (.sdf) in VS2010. After then I installed SQL Server at the moment, now I'd like to convert from .sdf to a "real" SQL Server database.

How can I do it ? Please advise.

Upvotes: 0

Views: 240

Answers (1)

Huske
Huske

Reputation: 9296

What you should to is to change your connectionString that points to your Compact SQL to your new SQL Server instance. After that in you Context file, inside of a static constructor which is called:

static YourDbContext()
{
    Database.SetInitializer(new CreateDatabaseIfNotExists<YourDbContext>());
}

This should create your database and tables based on your models. If you need to insert any data you should Enable-Migrations and in a configuration file that is createdc8 override Seed method.

One important thing DO NOT ASSUME that you have rights or privileges to CREATE or DROP DATABASE or to execute table modificiations.

I will assume that you used EF Code First approach. Your context file could look something like this:

public YourDbContext : DbContext
{
    static YourDbContext()
    {
        // Database.SetInitializer<DbContext>(null); // Change this line to the next one
        Database.SetInitializer(new CreateDatabaseIfNotExists<YourDbContext>());
    }

    // The rest of implementation 
}

Inside of Visual Studio in Package Manager Console execute:

Enable-Migrations -ProjectName YourProjectName

(If you have more than one DbContext implementation you will need to follow the instructions from the error message that Enable-Migrations throws back at you.)

Once this is done you will notice a new folder Migrations with one file Configuration.cs. Open it and you will see method Seed.

protected override void Seed(YourDbContext context)
{
    //  This method will be called after migrating to the latest version.
     //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
    //  to avoid creating duplicate seed data. E.g.
    //
    //    context.People.AddOrUpdate(
    //      p => p.FullName,
    //      new Person { FullName = "Andrew Peters" },
    //      new Person { FullName = "Brice Lambson" },
    //      new Person { FullName = "Rowan Miller" }
    //    );
    //

    // Here you can call your context.DbSetImplementation.Add(new Something {...});
}

That's about it.

Upvotes: 1

Related Questions