英文:
Adding Ids wit EFCore does not affect auto increment value PostgreSQL
问题
我正在使用PostgreSQL 15.0与EFCore结合使用。由于我希望一键设置演示环境,我在我的OnModelCreating(ModelBuilder modelBuilder)
方法中设置了modelBuilder.UseIdentityByDefaultColumns();
。
我的演示数据设置如下:
context.DropDowns.AddRange(new List<DropDown>()
{
new()
{
Id = 1,
Value = "Value1",
},
new()
{
Id = 2,
Value = "Value2",
},
});
我手动设置了ID,因为我使用这些ID来设置其他实体的FK值。但是,当我想要添加一个新的值(其中PostgreSQL应该自动生成ID)时,它会重用现有的PK,我会收到以下错误消息:
SQL错误[23505]:错误:违反唯一约束"PK_DropDowns"的重复关键值
详细信息:关键字("Id")=(2)已存在。
错误:违反唯一约束"PK_DropDowns"的重复关键值
详细信息:关键字("Id")=(2)已存在。
错误:违反唯一约束"PK_DropDowns"的重复关键值
详细信息:关键字("Id")=(2)已存在。
每次我点击保存时,它尝试使用的ID都会递增一次,所以在这个例子中,经过两次(因为我添加了两个具有固定ID的DropDown),它就能正常工作。我该如何处理使用自动生成的ID和手动设置ID混合的情况?
英文:
I am using PostgreSQL 15.0 in combination with EFCore. As I want to set up a demo environment with one click, I set modelBuilder.UseIdentityByDefaultColumns();
in my OnModelCreating(ModelBuilder modelBuilder)
method.
My demo data setup then looks like this:
context.DropDowns.AddRange(new List<DropDown>()
{
new()
{
Id = 1,
Value = "Value1",
},
new()
{
Id = 2,
Value = "Value2",
},
});
I manually set the ID as I use the IDs to set my FK values in other entities.
But when I then want to add a new value (where PostgreSQL should autogenerate the ID), it reuses an existing PK, and I get the following error message:
> SQL Error [23505]: ERROR: duplicate key value violates unique constraint "PK_DropDowns"
Detail: Key ("Id")=(2) already exists.
ERROR: duplicate key value violates unique constraint "PK_DropDowns"
Detail: Key ("Id")=(2) already exists.
ERROR: duplicate key value violates unique constraint "PK_DropDowns"
Detail: Key ("Id")=(2) already exists.
Every time I click on save, the ID it tries to use is incremented by one, so after two times in this example (as I added two DropDown
s with a fixed ID), it works fine. How could I handle this issue with mixed use of autogenerated Ids and manually set IDs?
答案1
得分: 0
I now use negative values as IDs in my demo data:
context.DropDowns.AddRange(new List<DropDown>()
{
new()
{
Id = -1,
Value = "Value1",
},
new()
{
Id = -2,
Value = "Value2",
},
});
英文:
I now use negative values as IDs in my demo data:
context.DropDowns.AddRange(new List<DropDown>()
{
new()
{
Id = -1,
Value = "Value1",
},
new()
{
Id = -2,
Value = "Value2",
},
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论