Cannot create a DbSet for 'Model' because this type is not included in the model for the context.

See original GitHub issue

Hi!

We recently updated EF Core from 2.0.2 to 2.1.2, and this code that worked perfectly fine earlier, has now started failing with some strange errors. When debugging this code in Visual Studio 2017, the error can not be reproduced. It only occurs when we have deployed this code to our Azure App Service.

We have a pretty basic Entity model that looks like this:

public class Model: IAudit
{
    [Key,
    DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public string Id { get; set; }

    [Required(ErrorMessage = "This field is required."),
    MaxLength(100, ErrorMessage = "This field may contain a maximum of {1} characters.")]
    public string Name { get; set; }

    public ICollection<AnotherModel> OherModels { get; set; }

    public DateTime Created { get; set; }
    public DateTime Updated { get; set; }
    public DateTime? Deleted { get; set; }
}

And in our DbContext, our OnModelCreating method looks like this:


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


protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);

     builder.Entity<Model>()
        .HasIndex(o => new { o.Name, o.App })
            .HasName("QueryAndSort");

    builder.Entity<Model>()
        .HasIndex(o => new { o.Deleted })
        .HasFilter("[Deleted] IS NULL")
        .HasName("NotDeleted");

    builder.Entity<AnotherModel>()
        .HasOne(o => o.Model)
        .WithMany(o => o.OherModels)
        .HasForeignKey(o => o.ModelId)
        .IsRequired()
        .OnDelete(DeleteBehavior.Restrict);

    builder.Entity<Model>();

    ...
}

We then run the following code to get the entity from the database:

return _context.Set<Model>()
    .AsNoTracking()
    .Where(o => o.Name == name)
    .ToList();

Since upgrading to 2.1.2 This now throws the following exception:

Exception message: Cannot create a DbSet for 'Model' because this type is not included in the model for the context.
Stack trace:
System.InvalidOperationException:
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.get_EntityType (Microsoft.EntityFrameworkCore, Version=2.1.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60)
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.get_EntityQueryable (Microsoft.EntityFrameworkCore, Version=2.1.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60)
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.System.Linq.IQueryable.get_Provider (Microsoft.EntityFrameworkCore, Version=2.1.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60)
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.Include (Microsoft.EntityFrameworkCore, Version=2.1.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60)
   at Project.Data.DAL.ModelRepository+<>c__DisplayClass6_0.<GetCached>b__0 (Project.Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=Project.Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null: C:\projects\Project.Data\DAL\ModelRepository.cs, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null: 49)

Strangely, all other entities in the project can be fetched with no problems, and we can also get the Model items from the database by including them in another query such as the one:

return _context.Set<AnotherModel>()
    .Include(o => o.Model)
    .FirstOrDefault(o => o.Id == id);

Further technical details

EF Core version: 2.1.2 Database Provider: Microsoft.EntityFrameworkCore.SqlServer Operating system: Windows at Azure App Service

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:3
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
priyanka-pasalkarcommented, Oct 12, 2021

Similar issue I was facing on Linux environment when using package - Microsoft.EntityFrameworkCore.SqlServer (2.1.4) Upgrading it to 2.2.6 has resolved the issue. This may help anyone.

0reactions
razzemanscommented, May 13, 2020

Just to chime in, I ran into this issue today, EF Core 3.1.3 packages. It breaks on:

   at Microsoft.EntityFrameworkCore.DbContext.Finder(Type type)
   at Microsoft.EntityFrameworkCore.DbContext.Find(Type entityType, Object[] 

I will try and reproduce the problem using a sample project, this happens deep in the code of our custom CMS so I would need to dive into this. However, I believe it is caused by ICollection <T> properties where T is an abstract class - I could fix it by preventing callingDbContext.Find on our abstract entity type and the error went away. That it may help anyone.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Cannot create a DbSet for 'Role' because this type is not ...
InvalidOperationException: Cannot create a DbSet for 'Role' because this type is not included in the model for the context. When the user ...
Read more >
How do I solve: cannot create a dbset for 'cusermasterlocal ...
How do I solve: cannot create a dbset for 'cusermasterlocal' because this type is not included in the model for the context.
Read more >
Error Cannot create a DbSet for 'GiftCardUsageHistory' ...
InvalidOperationException: Cannot create a DbSet for 'GiftCardUsageHistory' because this type is not included in the model for the context.
Read more >
DbContext.set() cannot create a DbSet for entity because this ...
[Solved]-DbContext.set() cannot create a DbSet for entity because this type is not included in the model for the context-entityframework core.
Read more >
C# – Cannot create a DbSet for 'IdentityUser' because this ...
C# – Cannot create a DbSet for 'IdentityUser' because this type is not included in the model for the context. asp.net-corec++.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found