如何解决无法添加实体类型“动物”的种子实体,因为没有为所需属性“ 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 = ""
},...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。