You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

EF Core中仅定义一个主键却提示无法创建多个ID的问题

解决“Cannot create Multiple Ids but yet I only have one”错误的方案

Hey there, let's work through why you're hitting this error even though you only have one [Key] marked property in your CustomerContracts class. Here are the most common fixes to try:

1. Check for EF's default key conventions

Entity Framework automatically treats properties named Id or [ClassName]Id as primary keys—even without the [Key] attribute. Double-check your full CustomerContracts class to make sure there isn't an extra property like CustomerContractsId (maybe a typo or leftover commented code) that EF is picking up as a second primary key.

2. Audit Fluent API configurations in your DbContext

If you're using Fluent API in your OnModelCreating method, it's easy to accidentally duplicate key configurations. Look for code like this:

// Correct configuration
modelBuilder.Entity<CustomerContracts>()
    .HasKey(c => c.ItemId);

// Accidental duplicate that causes conflict
modelBuilder.Entity<CustomerContracts>()
    .HasKey(c => c.SomeOtherProperty);

Delete any extra HasKey lines for CustomerContracts to ensure only ItemId is set as the primary key.

3. Reset your migrations and database from scratch

Sometimes old migration files hold onto stale configurations even after deleting the database. Try these steps:

  • Delete all existing migration files in your project's Migrations folder
  • Open Package Manager Console (or use the .NET CLI) and run:
    Add-Migration InitialCreate
    Update-Database
    
    This will generate a fresh migration and rebuild your database with the correct schema.

4. Verify no duplicate or conflicting attributes on your key property

Make sure you haven't accidentally added multiple [Key] attributes to ItemId (like [Key, Key, Column("ItemId")])—even a duplicate attribute can confuse EF. Also check for any third-party data annotations that might interfere with EF's primary key detection.

5. Check for inherited primary keys

If CustomerContracts inherits from a base class, the base class might already define a primary key property (like Id). This would make EF think there are two primary keys (one from the base, one from your subclass). You can fix this by explicitly marking ItemId as the key with [Key], or adjusting the base class's configuration if needed.

Start with the first two checks—they're the most likely culprits. If you're still stuck, sharing the full CustomerContracts class and your DbContext's OnModelCreating code would help narrow things down further.

内容的提问来源于stack exchange,提问作者David B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:41:20