Ninjanoel
Ninjanoel

Reputation: 2914

Entity Framework initialisation best practices

I wish to ensure Entity Framework never overwrites or tries to create the database I am connecting to. It is an established database previously accessed by ASP website (visual basic script flavour). I've seen the convention where you pass "name=" into the base constructor like so...

//example 1    
public class SchoolDBContext: DbContext 
{
    public SchoolDBContext() : base("name=SchoolDBConnectionString") 
    {
    }
}

BUT I'd prefer to NOT have it HARDCODED (like the above), so perhaps...

//example 2
public SchoolDBContext(string ConnectionString) : base("name=" + ConnectionString) {
}

BUT I'd also like to be able to bug out if the string is empty...

//example 3
public SchoolDBContext(string ConnectionString) :  {
    if (string.IsNullOrWhitespace(ConnectionString) throw Exception("empty connection string");
    base("name=" + ConnectionString);        
}

Question 1: I'm unsure if the third bit of code does the same job as the second, does it? As the third example may call the parameterless construction first before calling base with the "name="

Question 2: Is there options available in the constructor that can be used to configure EntityFramework more robustly?

I'm Using EF 6

Upvotes: 1

Views: 383

Answers (3)

Steven Van Eycken
Steven Van Eycken

Reputation: 566

Have a look at the DbMigrationsConfiguration.

You can create a new class SchoolDbContextConfiguration-class which inherrit from it and set AutomaticMigrationsEnabled to false.

    internal sealed class Configuration : DbMigrationsConfiguration<SchoolDBContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
    }
}

And in your SchoolDbContext initialize as follows:

public SchoolDBContext(string ConnectionString) : base("name=" + ConnectionString) {
var init = new MigrateDatabaseToLatestVersion<SchoolDBContext, SchoolDbContextConfiguration>(true);
        Database.SetInitializer(init);

}

Upvotes: 1

Cataklysim
Cataklysim

Reputation: 677

Question 1:

Im not sure either. I need to admit I never saw something like that in examples. May you tell us/me your documentation source or how you came up with that Idea?


Question 2: If you wan't a independence constructor, how about you try this?

    public SchoolDBContext()
        : base(ConnectionString == null ? "name=SchoolDBConnectionString" : WhateverYouDoIfItsWrong)
    {
        // Your code here! Lucky you
    }

Upvotes: 1

ohlmar
ohlmar

Reputation: 956

If you dont want EF to overwrite och create a new database every time you need to add the createinitializer class.

public class CreateInitializer : CreateDatabaseIfNotExists<SchoolDBContext>{}

Upvotes: 1

Related Questions