【问题标题】:The seed entity for entity type 'Animal' cannot be added because there was no value provided for the required property 'Id'.'无法添加实体类型“Animal”的种子实体,因为没有为所需的属性“Id”提供值。
【发布时间】:2020-11-09 19:45:13
【问题描述】:

当我运行我的项目时,它不断抛出这个错误。数据库存在,一切正常。有谁知道我的错误是什么?

错误发生在 EnsureCreated / EnsureDeleted。

错误:

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 = ""
        },...

【问题讨论】:

  • 这是什么意思 },.... 能否请您展示一下 animall 的完整代码
  • 如果您不提供主键值,IMigrationsModelDiffer 将不会知道记录是相同的..

标签: c# asp.net-mvc visual-studio


【解决方案1】:

你有一个外键 public int CategoryId { get;放; }。我认为您必须从 Category 开始,因为它看起来 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 = ""
        },...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-24
    • 1970-01-01
    • 1970-01-01
    • 2020-03-26
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    相关资源
    最近更新 更多