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

问题描述 投票:0回答:0

在 EF Core 中向

DbContext
添加实体时,我收到以下错误消息:

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

表示我有多个具有相同 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);          
}
c# entity-framework-core
© www.soinside.com 2019 - 2024. All rights reserved.