OnModelCreating is never called

I am starting to work with an entity. The 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 enter OnModelCreating when called:

  using (var context = new TestContext()) { } 

Where am I mistaken?

+4
c # entity-framework
Oct 12 '15 at 8:16
source share
3 answers

Try adding a new object to the context and save the changes.

how

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

By default, the strategy will try to create the database if it does not exist. Or at least throw an exception.

Or you can force it to create a database at startup

context.Database.Initialize (true);

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

+2
Oct. 12 '15 at 8:38
source share

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

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

If the database does not exist, it uses the information from the compiled model to create it. A model is created only once for each application. OnModelCreating will never be called when using the Database First approach. It will never be called because all mappings already exist in EDMX, so Code First and DbModelBuilder are never used.

Try calling a static initializer before calling SetInitializer:

 using (var context = new TestContext()) { Database.SetInitializer(new CreateDatabaseIfNotExists<EntityContext>()); context.Database.Initialize(true); } 
+4
Oct 12 '15 at 8:21
source share

In my case, this was because I left {get; set; } from my DBSet declaration. It took a while to figure it out!

0
Aug 24 '16 at 17:35
source share



All Articles