如何在同一事务中添加多个带有自动生成的ID的实体?

huangapple go评论67阅读模式
英文:

How to add multiple entities in same transaction with auto generated id?

问题

我在一个循环中有这段代码:

theTag = new ReportAdminTag() { Text = tag.Text };
_context.ReportAdminTag.Add(theTag);
_context.Entry(theTag).State = EntityState.Detached;
_context.SaveChanges();

但第二次循环时会抛出错误:

> 无法跟踪实体类型 'ReportAdminTag' 的实例,因为已经跟踪到具有相同键值 { 'Id' } 的另一个实例

这两个ID都是默认的Guid,因为我使用了mssql newid()来生成ID。

英文:

I have this in a loop

theTag = new ReportAdminTag() { Text = tag.Text };
_context.ReportAdminTag.Add(theTag);
_context.Entry(theTag).State = EntityState.Detached;
_context.SaveChanges();

but the second time through it throws an error

> The instance of entity type 'ReportAdminTag' cannot be tracked because
> another instance with the same key value for {'Id'} is already being
> tracked

The ID's are both the default Guid because I'm using mssql newid() to generate ids.

答案1

得分: 0

EF实现存在问题,与EF Core的InMemory Provider相关。

但是这个问题也可能发生在SQL Server上,与NewID()或NewSequentialID()函数的结果值相关。

因此,如果您在添加一个包含GUID列的新实体时创建一个GUID助手,似乎会更安全。

我建议将Guid.NewId()值与任何随机值结合起来生成32字节的base85编码(varchar(32)*)。

*) 将GUID列类型设置为varchar(32)。

英文:

It sounds there is problem on EF implemention, associated to EF Core's InMemory Provider.

However it can also occurs (duplication) on SQL Server, associated to result value of NewID() or NewSequentialID() function.

So it seems will be more safety if you create any guid helper to help EF when add a new entity which contains a guid column.

I suggest to combine Guid.NewId() value with any Random value to generate 32 bytes base85 encoded (varchar(32)*).

*) set guid column type to varchar(32).

答案2

得分: 0

我重新运行了 Scaffold-DbContext 以从数据库生成我的代码,然后事情开始正常工作起来。我可能进行了一些细微的更改,这些更改没有导致错误,而是导致了这种奇怪的行为。

这里的教训是不要带着未完成的工作去度假。

英文:

I re-ran Scaffold-DbContext to generate my code from the database and things started working. I probably made some minor change that wasn't resulting in an error and instead in this strange behavior.

Lesson here is don't go on vacation with uncompleted work.

huangapple
  • 本文由 发表于 2020年1月7日 01:03:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/59616156.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定