The entity type was not found. Ensure that the entity type has been added to the model

I'm new to ASP.NET Core and i'm trying to insert an entity into an Entity Framework Core model scaffolded from a simple existing MariaDB database.

This is the entity model:

    public class ScrapeAsincroni
    {
        public int Id { get; set; }
        public string Paese { get; set; }
        public string Engine { get; set; }
        public string Keywords { get; set; }
    }

This is the controller action that is supposed to add the entity:

    public JsonResult create(string paese, string engine, string keywords)
        {
            ScrapeAsincroni scrapeAsincrono = new ScrapeAsincroni {
                Paese = paese,
                Engine = engine,
                Keywords = keywords
            };
            _context.Add(scrapeAsincrono);

            try
            {
                _context.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                return Json(new Dictionary<string, int?> { { "id", null } });
            }
            return Json(new Dictionary<string, int?>{ {"id", scrapeAsincrono.Id} });
        }

The database context (_context) has been initialized on the controller's constructor. the line

 _context.Add(scrapeAsincrono);

throws the following exception:

System.InvalidOperationException: The entity type 'ScrapeAsincroni' was not found. Ensure that the entity type has been added to the model.

This is the modelBuilder code relative to this model

   public partial class ScraperDbContext : DbContext
    {
        public ScraperDbContext()
        {
        }

        public ScraperDbContext(DbContextOptions<ScraperDbContext> options)
            : base(options)
        {
        }

        public virtual DbSet<ScrapeAsincroni> ScrapeAsincroni { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                #warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
                optionsBuilder.UseMySql("server=51.255.74.100;port=3306;user=luca.ceccagnoli;password=Hb93#2ql;database=scraper_db", x => x.ServerVersion("10.3.25-mariadb"));
            }
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<ScrapeAsincroni>(entity =>
            {
                entity.HasComment("Informazioni su una ricerca asincrona dello Scraper");

                entity.Property(e => e.Id)
                    .HasColumnName("id")
                    .HasColumnType("int(11)");

                entity.Property(e => e.Engine)
                    .HasColumnName("engine")
                    .HasColumnType("varchar(255)")
                    .HasCharSet("utf8")
                    .HasCollation("utf8_general_ci");

                entity.Property(e => e.Keywords)
                    .IsRequired()
                    .HasColumnName("keywords")
                    .HasColumnType("text")
                    .HasCharSet("utf8")
                    .HasCollation("utf8_general_ci");

                entity.Property(e => e.Paese)
                    .HasColumnName("paese")
                    .HasColumnType("varchar(255)")
                    .HasCharSet("utf8")
                    .HasCollation("utf8_general_ci");
            });

            OnModelCreatingPartial(modelBuilder);
        }

        partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
    }         

I can't seem to understand why this happens, and couldn't find any solutions online.

2 answers

  • answered 2021-04-21 16:51 Ravi Maurya

    add

    public DbSet<ScrapeAsincroni> ScrapeAsincronis { get; set; }
    

    in your context file for adding an entity to your model.

  • answered 2021-04-22 06:46 Luca Ceccagnoli

    It was, of course, a trivial error that i would fix the next day. I was using the base DbContext class, while i should have used the custom database context class which i defined when scaffolding the database. This is how the context was instantiated before in the controller script:

            private readonly DbContext _context;
            public ScrapeAsincroniController(DbContext context)
            {
                _context = context;
            }
    

    now it is:

            private readonly ScraperDbContext _context;
            public ScrapeAsincroniController(ScraperDbContext context)
            {
                _context = context;
            }
    

    I also changed this line in startup.cs:

     services.AddDbContext<ScraperDbContext>(options => options
                    .UseMySql("<your_connection_string>",
                    mysqlOptions => mysqlOptions.ServerVersion(new Pomelo.EntityFrameworkCore.MySql.Storage.ServerVersion(new Version(10, 3, 25), ServerType.MariaDb))
                    )
                );