gpt4 book ai didi

c# - 找不到实体类型。确保实体类型已添加到模型中

转载 作者:行者123 更新时间:2023-12-05 02:42:56 25 4
gpt4 key购买 nike

我是 ASP.NET Core 的新手,我正在尝试将实体插入到从简单的现有 MariaDB 数据库搭建的 Entity Framework Core 模型中。

这是实体模型:

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

这是应该添加实体的 Controller 操作:

    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} });
}

数据库上下文 (_context) 已在 Controller 的构造函数中初始化。线路

 _context.Add(scrapeAsincrono);

抛出以下异常:

System.InvalidOperationException: The entity type 'ScrapeAsincroni' was not found. Ensure that the entity type has been added to the 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=#.#.#.#;port=####;user=####;password=####;database=####", 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);
}

我似乎不明白为什么会这样,也无法在线找到任何解决方案。

最佳答案

添加

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

在您的上下文文件中,用于将实体添加到您的模型。

关于c# - 找不到实体类型。确保实体类型已添加到模型中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67198831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com