【发布时间】: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