英文:
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 '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.
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 "Tasks" (
"Id" INTEGER NOT NULL,
"Description" TEXT NOT NULL,
CONSTRAINT "PK_Tasks" PRIMARY KEY("Id" AUTOINCREMENT)
);
Entity
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; }
}
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 = "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();
}
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 => x.Id)
.Where(g => g.Count() > 1)
.Select(y => y.Key)
.ToList();
but this returned 0.
Explicitly setting the key also did not help.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<OrderTask>()
.HasKey(x => 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!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论