16

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?

Raskolnikov
  • 3,791
  • 9
  • 43
  • 88
  • Possible duplicate of [EF 4.1 Code First - OnModelCreating call time](http://stackoverflow.com/questions/5634338/ef-4-1-code-first-onmodelcreating-call-time) – Roman Marusyk Oct 12 '15 at 08:45

4 Answers4

8

In my case this was happening because I had left the { get; set; } off my DBSet declaration. Took a while to figure that out!

Craig Fisher
  • 1,681
  • 2
  • 19
  • 26
6

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);
}
Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
  • How to call it again. My db is not created? – Raskolnikov Oct 12 '15 at 08:23
  • @Raskolnikov I've updated answer. Try to follow this – Roman Marusyk Oct 12 '15 at 08:47
  • I get exception : An exception of type 'System.Data.SqlClient.SqlException' occurred in EntityFramework.SqlServer.dll but was not handled in user code Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Specified LocalDB instance name is invalid. – Raskolnikov Oct 12 '15 at 09:03
  • 1
    Perfect explanation! – Mateusz Radny Jan 14 '18 at 20:32
  • This "ModelCaching" property no longer exists. See the answer: https://stackoverflow.com/a/50956210/288393 which talks about implementing the property "IDbModelCacheKeyProvider". – Tahir Hassan Dec 22 '19 at 19:27
4

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

Uber Bot
  • 511
  • 3
  • 8
  • I get exception : An exception of type 'System.Data.SqlClient.SqlException' occurred in EntityFramework.SqlServer.dll but was not handled in user code Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Specified LocalDB instance name is invalid. – Raskolnikov Oct 12 '15 at 09:03
  • Your Data Source=(LocalDB)\v11.0 appears to be incorrect. What MSSQL version are you using? – Uber Bot Oct 12 '15 at 09:05
  • I found solution. In last change I had (LocalDB)\\v11.0 ('\' two times). Thanks – Raskolnikov Oct 12 '15 at 09:10
0

As per the official MSDN doc,

It will be called only once as per the default behavior. called only once when the first instance of a derived context is created.

Maulik Boghara
  • 129
  • 1
  • 5