Raskolnikov Raskolnikov - 3 months ago 41
C# Question

OnModelCreating is never called

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?

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

Comments