gpt4 book ai didi

c# - 在 EntityFramworkCore.InMemory 提供程序中添加 Id = 0 的实体时出现问题

转载 作者:行者123 更新时间:2023-12-05 03:03:54 25 4
gpt4 key购买 nike

以下代码抛出异常:

System.InvalidOperationException: The instance of entity type 'DimEntity' cannot be tracked because another instance with the same key value for {'EntityEntityId'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached

var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
optionsBuilder.UseInMemoryDatabase("Test");
using (var dbContext = new MyDbContext(optionsBuilder.Options))
{
//when I comment this line, the rest works file
dbContext.DimEntity.Add(new DimEntity { EntityEntityId = 0, EntityKey = "Uknown" });


//otherwise this line throws the exception
dbContext.DimEntity.Add(new DimEntity { EntityEntityId = 1, EntityKey = "DFS Region" });
= "Europe Region" });
dbContext.DimEntity.Add(new DimEntity { EntityEntityId = 2, EntityKey = "Europe Region" });
}

为什么?

其他详细信息:

public partial class MyDbContext : DbContext
{
public MyDbContext (DbContextOptions<MyDbContext> options)
: base(options)
{
}

public virtual DbSet<DimEntity> DimEntity { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<DimEntity>(entity =>
{
entity.HasKey(e => e.EntityEntityId);
entity.ToTable("DimEntity", "mm");
entity.Property(e => e.EntityEntityId).HasColumnName("Entity_EntityID");
});
}
}

public partial class DimEntity
{
public int EntityEntityId { get; set; }
public string EntityKey { get; set; }
}

最佳答案

它不是特定于内存提供程序的。按照约定,int PK 被视为自动递增 (SqlServer identity),因此问题类似于向自动递增列添加显式值时的问题。

如果您将 new DimEntity { EntityEntityId = 0, ... } 保存在一个变量中,您将在 Add 之后看到 的值EntityEntityId 将为 1(因为当 PK 值为默认值(int 为 0)时,将执行 value generation on add)。

但是当您添加具有非默认 int PK 的实体时,不会生成任何值,并且会为 EntityEntityId = 1 抛出异常,因为它已经存在 - 生成的值您首先添加的第一个实体。

一般来说,如果您不想生成 PK 值,您应该在 OnModelCreating 中选择加入:

entity.Property(e => e.EntityEntityId)
.HasColumnName("Entity_EntityID")
.ValueGeneratedNever(); // <--

关于c# - 在 EntityFramworkCore.InMemory 提供程序中添加 Id = 0 的实体时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53416382/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com