Entity Framework Code First “Sequence contains more than one element”

Problem

When you run “update-database” in Package Manager Console, you see error “Sequence contains more than one element”.

Troubleshoot

The 1st step is to look the exception stack trace until you can locate the line of code that is causing the error:

   at My.Entity.Migrations.Configuration.Seed(MyContext context) in e:\MyApp\My.Entity\Migrations\Configuration.cs:line 89

So you can view what entity it is trying to AddOrUpdate.  Verify the following 3 things:

  1. You are specifying a unique key or a unique complex key.
  2. The objects you are trying to insert do not violate that uniqueness.
  3. The existing data in the database table do not violate that uniqueness.

To specify a unique complex key, use new { column1, column2, …}

For example,

context.AppSettings.AddOrUpdate(p => new { p.RunningEnv, p.AppMachineName, p.AppName,  p.AppKey },
new AppSetting { RunningEnv = "Dev", AppName = "App", AppMachineName = "dev2", AppKey = "MyName", AppValue = "xxxx", LastModified = DateTime.UtcNow }
);

Advertisements

One thought on “Entity Framework Code First “Sequence contains more than one element”

  1. Pingback: “Sequence contains one or more element” when running the Update-Database Seed() method in EF code-first migrations | thobanjalodut's Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s