Raskolnikov Raskolnikov - 1 year ago 136
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)

Connection string

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

I expect to go into OnModelCreating when I call:

using (var context = new TestContext())


Where I making mistake?

Answer Source

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


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

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