简体   繁体   中英

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

如果您不希望EF覆盖och,每次需要添加createinitializer类时都会创建一个新数据库。

public class CreateInitializer : CreateDatabaseIfNotExists<SchoolDBContext>{}

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
    }

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);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM