0

I have the following code:

public DataInitializer() {
            Database.SetInitializer<DataContext>(null);
            try {
                using (var context = new DataContext()) {
                    if (!context.Database.Exists())
                    {
                        ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                    }
                }

            }
            catch (Exception ex) {
                throw new InvalidOperationException("The Data database could not be initialized", ex);
            }
        }

and

 public class DataContext : DbContext
    {
        public DataContext() : base("xxdata") { }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }
        public DbSet<Application> Applications { get; set; }
    }

The code gets executed when I step through it but it seems like no database file is created (SQL Server Express).

Is there something obvious that I am doing wrong?

1 Answer 1

1

Create an inherited class as below;

public class DataContextInitializer : DropCreateDatabaseAlways<DataContext>
    {
        protected override void Seed(DataContext context)
        {
          //Seed data if you want
        }
    }

and add this to your Global.asax

protected void Application_Start()
{
    //Add your database initializer code 
    Database.SetInitializer(new DataContextInitializer());
}
Sign up to request clarification or add additional context in comments.

4 Comments

Just tried and it is saying "Has some invalid arguments". I will look into this a bit more.
@Gemma See my update.Previously , you had not inherited the class from some class like DropCreateDatabaseAlways<T> now put this class as you want. and check if it works.Also, you don't need to add any other details in this class as you have put CreateDatabase. EF will automatically create it for you.
I tried this but it seems to do nothing. Will it only work if I have something inside the Seed method? Maybe I need a constructor in DataContextInitializer ?
@Gemma No, its all right if you don't do seeding. tell me when are you loooking for a database? It will not be created until you try to add something in it. Try to add Application to the database through code. The database is created only when you make an instance of your context class or try to add something in database. try this, I think this is your problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.