Answered by:
How to stop EF Code First from generating the database

Question
-
I have accidentally named my connection string incorrectly for my ef code first project, which has resulted in the ef automatically building my database for me. How can I stop it from automatically building the database if I happen to do this again in the future - is there any way to just turn this off? Thanks!!
Thursday, May 19, 2011 3:26 AM
Answers
-
Hi jme1234,
Welcome!
If your connection string in configuration file, you should use <name=''connectionstringname">, it will look up the configuration file. An exception will be thrown if a connection string with the given name is not found(avoid generating database).
public class UnicornsContext : DbContext
{
public UnicornsContext()
: base("name=UnicornsCEDatabase")
{
}
}
More information you can refer here: http://blogs.msdn.com/b/adonet/archive/2011/01/27/using-dbcontext-in-ef-feature-ctp5-part-2-connections-and-models.aspx
Have a nice day.
Alan Chen[MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
- Marked as answer by jme1234 Thursday, May 19, 2011 12:52 PM
Thursday, May 19, 2011 8:32 AM -
You need to set initializer to your context
Database.SetInitializer<YourContext>(new MyInitializer());
YourContext context = new YourContext();add classpublic class MyInitializer:IDatabaseInitializer<YourContext>{public void InitializeDatabase(YourContext context){//check for existanceif (!context.Database.Exists()){//do something}}}Database will not be created, if you do like this. You can create it with context.Database.Create()
- Marked as answer by jme1234 Thursday, May 19, 2011 12:52 PM
Thursday, May 19, 2011 10:36 AM -
Hi jme1234
try this console app
class Program { static void Main(string[] args) { string connectionString = @"Data Source=.\SQLEXPRESS;Initial catalog=myDbTestBase;Integrated Security=True;Connect Timeout=30;User Instance=True;MultipleActiveResultSets=True"; DbDataContext firstContext = new DbDataContext(new FirstDbInitializer(),connectionString); try { Console.WriteLine(firstContext.Datas.Count()); } catch (Exception) { Console.WriteLine(firstContext.InitializerOutput); } connectionString = @"Data Source=.\SQLEXPRESS;Initial catalog=myDbTestBase1;Integrated Security=True;Connect Timeout=30;User Instance=True;MultipleActiveResultSets=True"; DbDataContext secondContext = new DbDataContext(new SecondDbInitializer(),connectionString); try { Console.WriteLine(secondContext.Datas.Count()); } catch (Exception) { Console.WriteLine(secondContext.InitializerOutput); } Console.ReadLine(); } } public class Data { public int Id { get; set; } public string Name { get; set; } } public class DbDataContext : DbContext { public DbDataContext(IDatabaseInitializer<DbDataContext> initializer,string connectionString) : base("name=MyConnectionStringName") { Database.Connection.ConnectionString = connectionString; Database.SetInitializer(initializer); } public string InitializerOutput=""; public DbSet<Data> Datas { get; set; } } public class FirstDbInitializer : IDatabaseInitializer<DbDataContext> { public void InitializeDatabase(DbDataContext context) { if (!context.Database.Exists()) { context.InitializerOutput = "First initializer. The database does not exist."; } } } public class SecondDbInitializer : IDatabaseInitializer<DbDataContext> { public void InitializeDatabase(DbDataContext context) { if (!context.Database.Exists()) { context.InitializerOutput = "Second initializer. The database does not exist."; } } }
The output is:
First initializer. The database does not exist.
Second initializer. The database does not exist.
Tuesday, May 24, 2011 5:02 AM
All replies
-
Hi jme1234,
Welcome!
If your connection string in configuration file, you should use <name=''connectionstringname">, it will look up the configuration file. An exception will be thrown if a connection string with the given name is not found(avoid generating database).
public class UnicornsContext : DbContext
{
public UnicornsContext()
: base("name=UnicornsCEDatabase")
{
}
}
More information you can refer here: http://blogs.msdn.com/b/adonet/archive/2011/01/27/using-dbcontext-in-ef-feature-ctp5-part-2-connections-and-models.aspx
Have a nice day.
Alan Chen[MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
- Marked as answer by jme1234 Thursday, May 19, 2011 12:52 PM
Thursday, May 19, 2011 8:32 AM -
You need to set initializer to your context
Database.SetInitializer<YourContext>(new MyInitializer());
YourContext context = new YourContext();add classpublic class MyInitializer:IDatabaseInitializer<YourContext>{public void InitializeDatabase(YourContext context){//check for existanceif (!context.Database.Exists()){//do something}}}Database will not be created, if you do like this. You can create it with context.Database.Create()
- Marked as answer by jme1234 Thursday, May 19, 2011 12:52 PM
Thursday, May 19, 2011 10:36 AM -
Thank you both - I will try out one of these!Thursday, May 19, 2011 12:53 PM
-
I read that I have to call this setinitializer in the application_onstart, or main() of my app, independently of the dbcontext - is there any way to just set this in the config file or anything, it seems really crappy that ef by default wants to create the database, and that to avoid it, in every application I use this in, which is going to be a web app, and several windows and wcf services, that I have to remember to turn off the database creation, or it gets generated. This is a scary prospect when dealing with a very large database environment and data layer.
Thursday, May 19, 2011 1:54 PM -
You can put Database.SetInitializer to constructor of your DbContext
Friday, May 20, 2011 4:51 AM -
It doesn't seem to work - and everything I keep reading says not to put it there, that it will only work when calling from your application initialization. So this works when you do it? I must be doing something wrong...I'll play around with this a bit more.
- Proposed as answer by Kirill Balashov Tuesday, May 24, 2011 4:58 AM
Friday, May 20, 2011 1:25 PM -
But then again...I always create my dbcontext everytime I call my data layer. So I have a class called UserService that has CRUD methods, among other things, and in each of those methods, I create a dbcontext and then use that to access or persist my data, depending on what I am doing.Friday, May 20, 2011 1:27 PM
-
Yes, this works when i do it.
method InitializeDatabase called only when you access data (or save)
I changed constructor of my dbcontext to
public MyDbContext(IDatabaseInitializer initializer, string connectionString)
and created some dbcontext with different initializers and connection strings each other (with data saving)
you can set initalizer anytime or drop it by setting null
Friday, May 20, 2011 8:37 PM -
I just tried this way to just set the name of the db, rather than use the initializer, and if I provide an incorrect name, it will try to create that database, so this method does not work, I will definitely have to go with the SetInitializer method.Tuesday, May 24, 2011 2:37 AM
-
I am trying to do this in my database context constructor, but it never calls the InitializeDatabase method (when I put a break point here, nothing is hit ever). ...this is the same thing I've read about other people having issues with, and thus, why everything I've read says not to put that here, but call the SetInitializer method from the application start. Here is my context and initializer:
public class DbDataContext : DbContext { public DbDataContext() : base("name=MyConnectionStringName") { Database.SetInitializer<DbDataContext>(new DbInitializer()); } } public class DbInitializer : IDatabaseInitializer<DbDataContext> { public void InitializeDatabase(DbDataContext context) { if (!context.Database.Exists()) { throw new NotSupportedException("The database does not exist."); } } }
Tuesday, May 24, 2011 3:05 AM -
Hi jme1234
try this console app
class Program { static void Main(string[] args) { string connectionString = @"Data Source=.\SQLEXPRESS;Initial catalog=myDbTestBase;Integrated Security=True;Connect Timeout=30;User Instance=True;MultipleActiveResultSets=True"; DbDataContext firstContext = new DbDataContext(new FirstDbInitializer(),connectionString); try { Console.WriteLine(firstContext.Datas.Count()); } catch (Exception) { Console.WriteLine(firstContext.InitializerOutput); } connectionString = @"Data Source=.\SQLEXPRESS;Initial catalog=myDbTestBase1;Integrated Security=True;Connect Timeout=30;User Instance=True;MultipleActiveResultSets=True"; DbDataContext secondContext = new DbDataContext(new SecondDbInitializer(),connectionString); try { Console.WriteLine(secondContext.Datas.Count()); } catch (Exception) { Console.WriteLine(secondContext.InitializerOutput); } Console.ReadLine(); } } public class Data { public int Id { get; set; } public string Name { get; set; } } public class DbDataContext : DbContext { public DbDataContext(IDatabaseInitializer<DbDataContext> initializer,string connectionString) : base("name=MyConnectionStringName") { Database.Connection.ConnectionString = connectionString; Database.SetInitializer(initializer); } public string InitializerOutput=""; public DbSet<Data> Datas { get; set; } } public class FirstDbInitializer : IDatabaseInitializer<DbDataContext> { public void InitializeDatabase(DbDataContext context) { if (!context.Database.Exists()) { context.InitializerOutput = "First initializer. The database does not exist."; } } } public class SecondDbInitializer : IDatabaseInitializer<DbDataContext> { public void InitializeDatabase(DbDataContext context) { if (!context.Database.Exists()) { context.InitializerOutput = "Second initializer. The database does not exist."; } } }
The output is:
First initializer. The database does not exist.
Second initializer. The database does not exist.
Tuesday, May 24, 2011 5:02 AM -
Well not sure what is going on, but what I sent here that what I was doing is now working, so that little code snippet I provided does work. Maybe it's just that it never calls the initializer until I access something on one of my DbSet's. So at least that is going for me now. Also, it runs the InitializeDatabase method every time I access any DbSet, or a property on any returned DbSet that is. Is that what it should be doing (does it always do that on whatever default initializer it uses if you don't provide one as well?)? I'm wondering, because this is going to get called every time I call a database access method on my data layer class like this for example:
/// <summary> /// Get all entities in the repository. /// </summary> public List<MyEntity> GetAll() { using (var db = new DbDataContext()) { return db.MyEntities.ToList(); // By accessing MyEntities, the InitializeDatabase method will be called on my initializer class, which will throw an exception if the database does not exist } } /// <summary> /// Insert an entity. /// </summary> /// <param name="entity">The entity to insert.</param> /// <returns>The id of the entity.</returns> public int Insert(MyEntity entity) { using (var db = new DbDataContext()) { db.MyEntities.Add(entity); db.SaveChanges(); } return entity.Id; }
Tuesday, May 24, 2011 1:26 PM