[c#] 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
    _context.SyncObjectState(entity);
}

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() :
        base("DimensionWebContext")
    {
        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.

This question is related to c# entity-framework ef-code-first dbcontext

The answer is


map of the entity (even an empty one) added to the configuration will lead to having the entity type be part of the context. We had an entity with no relationship to other entities that was fixed with an empty map.


Delete the .edmx file and add it again. Especially, if you have upgraded the Entity Framework.


I get same problem in Entity Framewrok and I solved it by under steps :

1-Open your Model.edmx 2-change a table place (for do change in cs file) 3-save it

I hope help you


For me it was caused because I renamed the entity class.When I rolled it back it was Ok.


My issue was resolved by updating the metadata part of the connection string. Apparently it was pointing at the wrong .csdl / .ssdl / .msl reference.


The problem may be in the connection string. Ensure your connection string is for SqlClient provider, with no metadata stuff related to EntityFramework.


For me, the problem was that I used:

List<Some> someCollection ...;
_dbContext.Remove(someCollection);

instead of:

_dbContext.RemoveRange(someCollection);

Visual Studio 2019 seems to cause this for me. I fixed it by generating the edmx model again in 2017.


You may try removing the table from the model and adding it again. You can do this visually by opening the .edmx file from the Solution Explorer.

Steps:

  1. Double click the .edmx file from the Solution Explorer
  2. Right click on the table head you want to remove and select "Delete from Model"
  3. Now again right click on the work area and select "Update Model from Database.."
  4. Add the table again from the table list
  5. Clean and build the solution

For me the issue was that I used the connection string generated by ADO.Net Model (.edmx). Changing the connection string solved my issue.


The message was pretty clear but I didn't get it at first...

I'm working with two Entity Framework DB contexts sysContext and shardContext in the same method.

The entity I had modified\updated is from one context but then I tried to save it to the other context like this:

invite.uid = user.uid;

sysContext.Entry(invite).State = EntityState.Modified;

sysContext.SaveChanges(); // Got the exception here

but the correct version should be this:

invite.uid = user.uid;

shardContext.Entry(invite).State = EntityState.Modified;

shardContext.SaveChanges();

After passing the entity to the correct context this error went away.


if you are trying DB first then be sure that your table has primary key


Apparently, this error is very generic, it could have a number of reasons. In my case, it was the following: The connection string (in Web.config) generated by the .edmx was invalid. After almost a day of trying everything, I changed the connection string from the EF string to an ADO.NET string. This solved my issue.

For example, the EF string looks something like this:

<connectionStrings> 
  <add name="BlogContext"  
    connectionString="metadata=res://*/BloggingModel.csdl| 
                               res://*/BloggingModel.ssdl| 
                               res://*/BloggingModel.msl; 
                               provider=System.Data.SqlClient 
                               provider connection string= 
                               &quot;data source=(localdb)\v11.0; 
                               initial catalog=Blogging;
                               integrated security=True; 
                               multipleactiveresultsets=True;&quot;" 
     providerName="System.Data.EntityClient" /> 
</connectionStrings>

And the ADO.NET string looks like this:

<connectionStrings>
  <add name="BlogContext"  
        providerName="System.Data.SqlClient"  
        connectionString="Server=.\SQLEXPRESS;Database=Blogging;
        Integrated Security=True;"/> 
</connectionStrings>

Source: http://msdn.microsoft.com/nl-nl/data/jj556606.aspx


This can also occur if you are using a persisted model cache which is out of date for one reason or another. If your context has been cached to an EDMX file on a file system (via DbConfiguration.SetModelStore) then OnModelCreating will never be called as the cached version will be used. As a result if an entity is missing from your cached store then you will get the above error even though the connection string is correct, the table exists in the database and the entity is set up correctly in your DbContext.


I had this

using (var context = new ATImporterContext(DBConnection))
{
    if (GetID(entity).Equals(0))
    {
        context.Set<T>().Add(entity);
    }
    else
    {
        int val = GetID(entity);
        var entry = GetEntryAsync(context, GetID(entity)).ConfigureAwait(false);
        context.Entry(entry).CurrentValues.SetValues(entity);

    }
    
    await context.SaveChangesAsync().ConfigureAwait(false);
}

This was in an async method, but I've forgot to put await before GetEntryAsync, and so I got this same error...


One other thing to check with your connection string - the model name. I was using two entity models, DB first. In the config I copied the entity connection for one, renamed it, and changed the connection string part. What I didn't change was the model name, so while the entity model generated correctly, when the context was initiated EF was looking in the wrong model for the entities.

Looks obvious written down, but there are four hours I won't get back.


I was facing the same issue with EntityFrameworkCore trying to update a range of values.

This approach did not work

  _dbSet.AttachRange(entity);
  _context.Entry(entity).State = EntityState.Modified;
   await _context.SaveChangesAsync().ConfigureAwait(false);

After adding UpdateRange method and removing attach and entry everything work

  _dbSet.UpdateRange(entity);
  await _context.SaveChangesAsync().ConfigureAwait(false);

Sounds obvious, but make sure that you are not explicitly ignoring the type:

modelBuilder.Ignore<MyType>();


Could be stupid, but if you only got this error on some Table, dont forget to clean your project and rebuild (could save a lot of time)


For me the issue was that I had not included the Entity Class within my db set inside the context for entity framework.

public DbSet<ModelName> ModelName { get; set; }

I've seen this error when an existing table in the database doesn't appropriately map to a code first model. Specifically I had a char(1) in the database table and a char in C#. Changing the model to a string resolved the problem.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to entity-framework

Entity Framework Core: A second operation started on this context before a previous operation completed EF Core add-migration Build Failed Entity Framework Core add unique constraint code-first 'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked Auto-increment on partial primary key with Entity Framework Core Working with SQL views in Entity Framework Core How can I make my string property nullable? Lazy Loading vs Eager Loading How to add/update child entities when updating a parent entity in EF

Examples related to ef-code-first

EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType There is already an object named in the database The entity type <type> is not part of the model for the current context Entity Framework 6 Code first Default value Unique Key constraints for multiple columns in Entity Framework Entity Framework (EF) Code First Cascade Delete for One-to-Zero-or-One relationship Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why? How to delete and recreate from scratch an existing EF Code First database Entity Framework: One Database, Multiple DbContexts. Is this a bad idea? Ignoring a class property in Entity Framework 4.1 Code First

Examples related to dbcontext

The entity type <type> is not part of the model for the current context Entity Framework: One Database, Multiple DbContexts. Is this a bad idea? One DbContext per web request... why? How to fix the datetime2 out-of-range conversion error using DbContext and SetInitializer? How to update only one field using Entity Framework?