EF Core – 添加实体时出现重复错误

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

EF Core - duplicate error when adding entities

问题

在将实体添加到EF Core的DbContext时,我收到以下错误消息:

“实体类型的实例 'OrderTask' 无法跟踪,因为已经有具有键值 '{Id: 1}' 的另一个实例正在被跟踪。在附加现有实体时,请确保只附加一个具有给定键值的实体实例。”

这表明我有多个具有相同Id(Id:1)的实体。但事实并非如此。
对于此错误的源头或如何调试它是否有任何建议将不胜感激。

数据库

CREATE TABLE "Tasks" (
	"Id"	INTEGER NOT NULL,
	"Description"	TEXT NOT NULL,
	CONSTRAINT "PK_Tasks" PRIMARY KEY("Id" AUTOINCREMENT)
);

实体

public class OrderTask : BaseEntity<int>
{
    public string Description { get; set; }
    public ICollection<Machine> Machines { get; set; }
}

public class BaseEntity<T> where T : struct
{
    public T Id { get; set; }
}

适配器

public async Task AddOrUpdateTasks()
{
    using var cn = new SqlConnection(_cn);
    await cn.OpenAsync();
    var cmd = new SqlCommand();
    cmd.CommandType = System.Data.CommandType.StoredProcedure;
    cmd.CommandText = "usp_Task_Sel_All";
    cmd.Connection = cn;

    using var dr = await cmd.ExecuteReaderAsync();
    while (await dr.ReadAsync())
        _orderContext.Tasks.Add(new OrderTask() { Id = (int)dr["TaskNumber"], Description = (string)dr["TaskDescription"] });

    await _orderContext.SaveChangesAsync();
}

方法

public async Task EFWorkcenterTest()
{
    var orderContext = new OrderContext();
    orderContext.Database.EnsureDeleted();
    orderContext.Database.EnsureCreated();

    var adapter = new Adapter(orderContext);
    await adapter.AddOrUpdateTasks();
}

我已经尝试使用以下方式检查重复项:

var dup = _orderContext.Tasks.GroupBy(x => x.Id)
    .Where(g => g.Count() > 1)
    .Select(y => y.Key)
    .ToList();

但这返回了0。

显式设置键也没有帮助。

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<OrderTask>()
        .HasKey(x => x.Id);          
}

希望这些信息对你有所帮助。

英文:

When adding entities to a DbContext in EF Core I get following error message:

The instance of entity type &#39;OrderTask&#39; cannot be tracked because another instance with the key value &#39;{Id: 1}&#39; is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.

Indicating I have multiple entities with the same Id (Id:1). But this is not the case.
Any suggestions on the source of this error or how to debug it would be appreciated.

Database

CREATE TABLE &quot;Tasks&quot; (
	&quot;Id&quot;	INTEGER NOT NULL,
	&quot;Description&quot;	TEXT NOT NULL,
	CONSTRAINT &quot;PK_Tasks&quot; PRIMARY KEY(&quot;Id&quot; AUTOINCREMENT)
);

Entity

public class OrderTask : BaseEntity&lt;int&gt;
{
    public string Description { get; set; }
    public ICollection&lt;Machine&gt; Machines { get; set; }
}

public class BaseEntity&lt;T&gt; where T : struct
{
    public T Id { get; set; }
}

Adapter

public async Task AddOrUpdateTasks()
{
    using var cn = new SqlConnection(_cn);
    await cn.OpenAsync();
    var cmd = new SqlCommand();
    cmd.CommandType = System.Data.CommandType.StoredProcedure;
    cmd.CommandText = &quot;usp_Task_Sel_All&quot;;
    cmd.Connection = cn;

    using var dr = await cmd.ExecuteReaderAsync();
    while (await dr.ReadAsync())
        _orderContext.Tasks.Add(new OrderTask() { Id = (int)dr[&quot;TaskNumber&quot;], Description = (string)dr[&quot;TaskDescription&quot;] });


    await _orderContext.SaveChangesAsync();
}

Method

public async Task EFWorkcenterTest()
{
    var orderContext = new OrderContext();
    orderContext.Database.EnsureDeleted();
    orderContext.Database.EnsureCreated();

    var adapter = new Adapter(orderContext);
    await adapter.AddOrUpdateTasks();
}

I already tried checking for duplicates with

var dup = _orderContext.Tasks.GroupBy(x =&gt; x.Id)
              .Where(g =&gt; g.Count() &gt; 1)
              .Select(y =&gt; y.Key)
              .ToList();

but this returned 0.

Explicitly setting the key also did not help.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity&lt;OrderTask&gt;()
        .HasKey(x =&gt; x.Id);          
}

答案1

得分: 0

移除表上的AUTOINCREMENT就可以了!由于SqlCommand返回的第一个条目的Id = 0,EF Core或SQLite分配了值1。因此,从这一点开始,就有了两个重复的条目。

感谢@MikeMozhaev!

英文:

Removing AUTOINCREMENT on the table did it!
Since the first entry from the SqlCommand returned Id = 0, EF Core or SQLite assigned it the value 1. So after this point there were two duplicate entries.

Thanks to @MikeMozhaev!

huangapple
  • 本文由 发表于 2023年3月1日 15:08:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75600511.html
匿名

发表评论

匿名网友

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

确定