[英]Entity Framework Core attempting to update column marked as Identity in model
I have a database table where one of the columns is an IDENTITY
column (not the primary key which is set manually).我有一个数据库表,其中一列是
IDENTITY
列(不是手动设置的主键)。 My EF Core model looks like this:我的 EF Core 模型如下所示:
public class Model
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
...Other fields...
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int AnotherId { get; set; }
}
Despite the annotation, when I do an update on the table I find that the SQL which is generated tries to update the IDENTITY
column:尽管有注释,但当我对表进行更新时,我发现生成的 SQL 尝试更新
IDENTITY
列:
UPDATE [Model] SET ... [AnotherId] = @p10 ...
WHERE [Id] = @p29;
SELECT @@ROWCOUNT;
This obviously fails, causing the an exception to be thrown.这显然失败了,导致抛出异常。 I am using Entity Core 2.0 and upgrading to 2.1 is currently not an option.
我正在使用 Entity Core 2.0,目前无法升级到 2.1。 Any ideas why the data annotation is being ignored?
为什么数据注释被忽略的任何想法?
Try Fluent API in OnModelCreating
of the Context
class.在
Context
类的OnModelCreating
中尝试Fluent API 。 Something like this:像这样的东西:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder
.Entity<Model>()
.Property(c => c.AnotherId )
.UseSqlServerIdentityColumn();
}
Also in EF Core 2 it should be something like this:同样在 EF Core 2 中,它应该是这样的:
modelBuilder.Property(c => c.AnotherId).UseSqlServerIdentityColumn();
modelBuilder.Property(p => p.AnotherId )
.Metadata.AfterSaveBehavior = PropertySaveBehavior.Ignore;
The solution for me in EF Core 3.1 was this:我在 EF Core 3.1 中的解决方案是:
partial void OnModelCreatingPartial(ModelBuilder modelBuilder)
{
modelBuilder.Entity<YourTableName>().Property(c => c.YourPropertyName).UseIdentityColumn().ValueGeneratedOnAddOrUpdate();
}
Without ValueGeneratedOnAddOrUpdate() I was seeing the same error as the OP when updating existing records.如果没有 ValueGeneratedOnAddOrUpdate(),我在更新现有记录时看到了与 OP 相同的错误。 It looks therefore as though UseIdentityColumn() is equivalent to calling ValueGeneratedOnAdd().
因此,看起来 UseIdentityColumn() 等效于调用 ValueGeneratedOnAdd()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.