在EFCore中添加Ids不会影响自增值PostgreSQL。

huangapple go评论54阅读模式
英文:

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&lt;DropDown&gt;()
{
    new()
    {
        Id = 1,
        Value = &quot;Value1&quot;,
    },
    new()
    {
        Id = 2,
        Value = &quot;Value2&quot;,
    },
});

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 DropDowns 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&lt;DropDown&gt;()
{
    new()
    {
        Id = -1,
        Value = &quot;Value1&quot;,
    },
    new()
    {
        Id = -2,
        Value = &quot;Value2&quot;,
    },
});

huangapple
  • 本文由 发表于 2023年6月11日 21:56:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76450813.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定