gpt4 book ai didi

c# - 更改跟踪器不会将正确的后续 ID 分配给新插入的实体

转载 作者:行者123 更新时间:2023-11-30 12:21:17 25 4
gpt4 key购买 nike

我已经从 webapi 模板创建了一个新的 .NET Core 项目并添加了一个模型类:

public class Todo {
public int Id { get; set; }
public string Name { get; set; }
}

我的上下文类:

public SoContext: DbContext {
public SoContext(DbContextOptions<SoContext> options) { base(options); }
public DbSet<Todo> Todos { get; set; }
}

我已经注册了这样的上下文:

public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<SoContext>(opt => opt.UseInMemoryDatabase("SO"));
services.AddMvc();
}

我想我应该像这样播种上下文:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, SoContext context)
{
app.UseMvc();
context.Todos.Add(new Todo() { Id = 1, Name = "1" });
context.SaveChanges(); // This works okay!
}

它工作正常......但是在我的请求处理程序中,甚至在 Configure 之后,当我运行这个时:

context.Todos.Add(new Todo() { Name = "non-seed" });
context.SaveChanges(); // Uh - oh

我得到:

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

在我看来,更改跟踪器应该已经想出将 2 的 ID 分配给 non-seed Todo,不?为什么不是这样?

我尝试使用 Attach 而不是为具有 key 的实体添加,即使它没有任何意义,而且确实没有任何区别。

Here's a GitHub repository that demonstrates the problem

最佳答案

更新:现在可以在 .NET Core 3.0 中使用! You can see a showcase here .

我在 comment in the GitHub repository for EntityFrameworkCore 中得到了这个问题的答案.

When using database-generated keys at the same time as keys chosen by the application it is the responsibility of the application to not choose keys that collide with those generated by the database.

这意味着目前,要么数据库使用缺少键的实体进行播种(因此需要使用导航属性而不是 ID 来设置任何关系),要么使用原始 SQL 并让 FE 获取已经播种的数据库(谢谢,@Nicolaus - 虽然我认为这不适用于内存)。

We could make the key generator in the in-memory database smarter, so leaving this open to discuss in triage, but I think even if we decide to do so, it will likely be low priority.

关于c# - 更改跟踪器不会将正确的后续 ID 分配给新插入的实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46018654/

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