无法添加实体类型“动物”的种子实体,因为没有为所需属性“ Id”提供任何值

问题描述

当我运行项目时,它会不断抛出此错误。该数据库已存在,并且一切正常。有人知道我的错误吗?

错误发生在确保创建/确保删除

错误

system.invalidOperationException:'无法添加实体类型'Animal'的种子实体,因为没有为所需属性'Id'提供任何值。'

代码

public class Animal
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public string Picture { get; set; }
    public string Description { get; set; }
    [ForeignKey("Category")]
    public int CategoryId { get; set; }
    public Category Category { get; set; }
}

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        string connectionString = "Server=(localdb)\\AnimalShopProject;Database=PetShop;Trusted_Connection=true";
        services.AddDbContext<AnimalContext>(options => options.UsesqlServer(connectionString));
        services.AddControllersWithViews();
    }
    public void Configure(IApplicationBuilder app,AnimalContext ctx)
    {
        ctx.Database.EnsureDeleted();
        ctx.Database.EnsureCreated();

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute("Default","{controller=AnimalShop}/{action=Index}");
        });
    }
}
public class AnimalContext : DbContext
{
    public AnimalContext(DbContextOptions<AnimalContext> options) : base(options)
    {
    }

    public DbSet<Animal> Animals { get; set; }
    public DbSet<Category> Categories { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Animal>().HasData(          

        #region AddingAquatics
        new Animal
        {
            Id = 1,Name = "Shark",Age = 5,CategoryId = 1,Picture = "images/shark.jpg",Description = ""
        },...

解决方法

您有一个外键公共int CategoryId {get;组; }。我认为您必须从Category开始,因为它看起来像表Category的第一个Animal记录没有Id = 1。

modelBuilder.Entity<Category>().HasData(    

new Category{
CategoryId=1,Name=.......
} 
);     

       
 modelBuilder.Entity<Animal>().HasData(          

           new Animal
        {
            Id = 1,Name = "Shark",Age = 5,CategoryId = 1,Picture = "images/shark.jpg",Description = ""
        },...