Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Short Walks: System.InvalidOperationException — How to Deal With It [Snippet]

DZone's Guide to

Short Walks: System.InvalidOperationException — How to Deal With It [Snippet]

Here's how to address a little-known issue — "The seed entity for entity type 'MyEntity' cannot be added..." — with EF Core 2.

· Integration Zone ·
Free Resource

SnapLogic is the leading self-service enterprise-grade integration platform. Download the 2018 GartnerMagic Quadrant for Enterprise iPaaS or play around on the platform, risk free, for 30 days.

I got this error recently while playing with EF Core 2. There's very little on Google about it, and although it's not a hugely difficult problem to solve, if I ever get it again, I can just Google it!

The error:

System.InvalidOperationException: "The seed entity for entity type 'MyEntity' cannot be added because another seed entity with the same key value for {'Id'} has already been added. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values."

It is effectively caused by a conflict in the primary key, and it gives you the first step towards solving it in the error (in OnModelCreating):

var options =
    new DbContextOptionsBuilder<ApplicationDbContext>()
         .UseSqlServer(configuration.GetConnectionString("DefaultConnection"))
         .EnableSensitiveDataLogging()
         .Options;


Now it says:

System.InvalidOperationException: "The seed entity for entity type 'MyEntity' cannot be added because another seed entity with the key value 'Id:1′ has already been added."

In my particular case, I'd been playing around with adding some seed data, and had left this in (OnModelCreating):

modelBuilder.Entity<MyEntity>().HasData(new Data.MyEntity()
{
    Id = 1,
    Name = "Test",
    CreatedDate = new DateTime(2018, 07, 03),
    UpdatedDate = new DateTime(2018, 07, 03)
});

Download A Buyer's Guide to Application and Data Integration, your one-stop-shop for research, checklists, and explanations for an application and data integration solution.

Topics:
entity framework core ,c# ,integration ,databases ,exception

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}