The entity type is not part of the model for the current context

c# dbcontext ef-code-first entity-framework


I am learning Entity Framework, but I'm not sure if I am following the code-first methodology correctly.

I have generated my entities and am using a generic repository pattern based on the code from

But I encounter the following issues when I attempt to access or alter the entity:

System.InvalidOperationException: The entity type Estate is not part of the model for the current context.

When I try to access it from my repository, this problem occurs:

public virtual void Insert(TEntity entity)
    ((IObjectState)entity).ObjectState = ObjectState.Added;
    _dbSet.Attach(entity); // <-- The error occurs here

The entities (tables) are not created at starting, but the database (./SQLEXPRESS) is built perfectly.

Do I need to explicitly set the mapping of the entities, I wonder. Why can't EF do this on its own?

I am my entity.

public class Estate : EntityBase
    public int EstateId { get; set; }
    public string Name { get; set; }

Following is my context:

public partial class DimensionWebDbContext : DbContextBase // DbContextBase inherits DbContext
    public DimensionWebDbContext() :
        Database.SetInitializer<DimensionWebDbContext>(new CreateDatabaseIfNotExists<DimensionWebDbContext>());
        Configuration.ProxyCreationEnabled = false;

    public new IDbSet<T> Set<T>() where T : class
        return base.Set<T>();


Is there a particular cause for this error? Without any success, I also tried turning on automatic migrations and enabling migrations.

12/19/2013 6:34:58 PM

Accepted Answer

Add that to your customDbContext class:

protected override void OnModelCreating(DbModelBuilder modelBuilder)

This explains why your tables might not be created at startup. In the OnModelCreating method override, you must inform the DbContext about them.

Here, you may either create unique mappings for each item or break them up into separateEntityTypeConfiguration<T> classes.

12/19/2013 6:41:19 PM

Popular Answer


Related Questions


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