janhartmann janhartmann - 2 months ago 44
C# Question

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

I am getting into the Entity Framework, but I am unsure if I am missing a critical point in the code-first approach.

I am using a generic repository pattern based on the code from https://genericunitofworkandrepositories.codeplex.com/ and have created my entities.

But when I try to access or modify the entity I run into the following:

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

It happens when I am trying to access it from my repository:

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

The database (./SQLEXPRESS) is created just fine, but the entities (tables) is just not created on startup.

I am wondering if I need to explicit set the mapping of the entities? Is EF not able to this by its own?

My Entity is:

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

My context is as so:

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 any specific reason why this error occurs? I have tried enable migrations and enable automatic migrations without any help either.


Put this in your custom DbContext class:

protected override void OnModelCreating(DbModelBuilder modelBuilder)

If your tables are not created on startup, this is why. You need to tell the DbContext about them in the OnModelCreating method override.

You can either do custom per-entity mappings here, or separate them out into separate EntityTypeConfiguration<T> classes.