Entity Framework Code First主键冲突问题求助
Hey Andrea, let's break down why you're hitting that primary key conflict when adding Invoices instances, and walk through actionable fixes to resolve it.
Common Causes & Solutions
1. You're manually assigning duplicate Guid values to primary keys
If you're explicitly setting the Id property on either Invoices or Payments instances (e.g., reusing the same Guid across multiple objects), this will immediately trigger a conflict when EF tries to insert them into the database.
Fix:
- Let Entity Framework auto-generate unique Guid values for you. You can enforce this with data annotations directly on your entities:
public class Invoices { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public Guid Id { get; set; } public Customers Customer { get; set; } public List<Payments> Payments { get; set; } public Double Total { get; set; } public DateTime Date { get; set; } public Boolean Payed { get; set; } } public class Payments { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public Guid Id { get; set; } public Products Product { get; set; } public Int32 Quantity { get; set; } } - Alternatively, use Fluent API in your
DbContextto configure the generation strategy globally:protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Invoices>() .Property(i => i.Id) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); modelBuilder.Entity<Payments>() .Property(p => p.Id) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); } - If you must manually set Guids, ensure every new instance gets a unique
Guid.NewGuid()value—never reuse the same Guid across multiple objects.
2. Conflict with related entities (Customers/Products)
When you add an Invoices instance, EF will try to insert any related Customers or Products that aren't already tracked by the context. If those related entities have an Id that already exists in the database, you'll get a primary key conflict.
Fix:
- For existing
CustomersorProducts, attach them to the context first so EF knows to link them instead of inserting duplicates:// Fetch the existing customer from the database (EF will track it) var existingCustomer = dbContext.Customers.Find(existingCustomerId); // Fetch the existing product var existingProduct = dbContext.Products.Find(existingProductId); var addInvoice = new Invoices { Customer = existingCustomer, // Link to the tracked existing customer Payments = new List<Payments> { new Payments { Product = existingProduct, Quantity = 3 } // Link to tracked existing product }, Total = 150.0, Date = DateTime.Now, Payed = false }; dbContext.Invoices.Add(addInvoice); dbContext.SaveChanges(); - If you're creating new related entities, make sure their
Idproperties are either auto-generated (as shown above) or set to unique Guids.
3. Accidental duplicate entries in your Payments list
If you're adding multiple Payments to the same invoice but accidentally using the same Id for multiple payment instances, this will cause a conflict when EF tries to insert them.
Fix:
- Double-check your code that builds the
Paymentslist. Ensure each payment gets a uniqueId(or let EF auto-generate it):// Correct example: Each payment gets a unique auto-generated Id var addInvoice = new Invoices { // ... other invoice properties Payments = new List<Payments> { new Payments { Product = product1, Quantity = 2 }, new Payments { Product = product2, Quantity = 5 }, new Payments { Product = product3, Quantity = 1 } } };
Quick Debugging Steps
- Check the exact exception message—it will explicitly tell you which entity (Invoices/Payments/Customers/Products) is causing the conflict.
- Inspect the
Idvalues of all entities you're trying to insert right before callingSaveChanges(). - Verify that related entities either exist in the database (and are tracked by the context) or are new with unique identifiers.
内容的提问来源于stack exchange,提问作者Andrea Drago

