我正在将 Asp.Net Core 1.1 应用程序升级到 Asp.Net Core 2.0。
我在所有 Entity Framework 2.0 查询中都遇到了一个常见错误:
System.InvalidOperationException: The property 'Id' cannot be
configured as 'ValueGeneratedOnUpdate' or 'ValueGeneratedOnAddOrUpdate'
because the key value cannot be changed after the entity has been
added to the store.
此错误是通过以下查询获得的:
var themes = await _context.Themes.ToListAsync();
主题实体如下:
public class Theme
{
public Int32 Id { get; set; }
public String Name { get; set; }
public virtual ICollection<Book> Books { get; set; }
} // Theme
其配置如下:
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<Theme>(b =>
{
b.ToTable("Themes");
b.HasKey(x => x.Id);
b.Property(x => x.Id).UseSqlServerIdentityColumn();
b.Property(x => x.Name).IsRequired(true).HasMaxLength(200);
b.HasIndex(x => x.Name).IsUnique();
});
}
在项目启动中,我有以下内容:
services.AddDbContext<Context>(x => x.UseSqlServer(connectionString));
我尝试了不同的查询和实体,但我不断收到此错误。
我错过了什么?