升级到EF Core 2.0:System.InvalidOperationException:属性' Id'无法配置为' ValueGeneratedOnUpdate'

时间:2017-09-12 19:16:12

标签: c# asp.net-core entity-framework-core ef-core-2.0

我正在将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();
    });
}

在Startup项目中,我有以下内容:

services.AddDbContext<Context>(x => x.UseSqlServer(connectionString));

我尝试了不同的查询和实体,我不断收到此错误。

我错过了什么?

1 个答案:

答案 0 :(得分:0)

据我了解您的问题,您无法为Id属性设置自动增量。

只需删除行b.Property(x => x.Id).UseSqlServerIdentityColumn();b.HasIndex(x => x.Name).IsUnique();,因为HasKey已经设置了自动增量。有关详细信息,请阅读此MS docs article - Keys (primary)。 我也删除了表映射,因为默认情况下激活表名复数

您的OnModelCreating应该如下:

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);

    builder.Entity<Theme>(b => {

        b.HasKey(x => x.Id);

        b.Property(x => x.Name).IsRequired(true).HasMaxLength(200);
    });
}

仅为了便于阅读,我更愿意使用以下代码:

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);

    var themeEntity = builder.Entity<Theme>();

    themeEntity.HasKey(x => x.Id);

    themeEntity.Property(x => x.Name)
        .HasMaxLength(200)
        .IsRequired(true);
}

更好的方法是将实体配置提取到他们实现IEntityTypeConfiguration<T>configuration separation)的自己的类中。