OnModelCreating is never called

c# entity-framework

Question

I am starting work with entity framework. Problem is that my OnModelCreating method is never called.

this is my context class:

public class TestContext : DbContext
    {
        public TestContext()
            : base("name=TestDBConnectionString")
        { }

        public DbSet<WorkItem> WorkItems { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }
    }

Connection string

 <add name="TestDBConnectionString"
      connectionString="Data Source=(LocalDB)\v11.0;Initial Catalog=TestDB;Integrated Security=true"
      providerName="System.Data.SqlClient"/>

I expect to go into OnModelCreating when I call:

 using (var context = new TestContext())
        {

        }

Where I making mistake?

1
9
10/12/2015 8:16:46 AM

Accepted Answer

Try to add a new entity to the context and persist changes.

Like

using (var context = new TestContext())
{
    context.WorkItem.Add(new WorkItem()); //Construct valid entity
    context.SaveChanges();
}

By default strategy, it will try to create a database, if it doesn't exist. Or at least will throw an exception.

Or you can force it to create database at start up

context.Database.Initialize(true);

https://msdn.microsoft.com/en-us/library/system.data.entity.database.initialize(v=vs.113).aspx

3
10/12/2015 8:44:14 AM

Popular Answer

This method is called when the model for a derived context has been initialized, but before the model has been locked down and used to initialize the contex.

Typically, this method is called only once when the first instance of a derived context is created. The model for that context is then cached and is for all further instances of the context in the app domain. This caching can be disabled by setting the ModelCaching property on the given ModelBuidler, but note that this can seriously degrade performance.
See MSDN

If the database doesn't exists it uses information from compiled model to create it. The model is created only once per application. OnModelCreating will never be called when using the Database First approach. It will never be called because all the mappings already exist in the EDMX and so Code First and the DbModelBuilder are never used.

Try to call to the static initializer before making the SetInitializer call:

using (var context = new TestContext())
{
    Database.SetInitializer(new CreateDatabaseIfNotExists<EntityContext>());
    context.Database.Initialize(true);
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow