0
votes

When I run the following code in my Seed method, the Package manager Console keeps throwing a "Sequence contains no elements" error.

context.Countries.AddOrUpdate(c => c.Name,
    new Country { IsInUse = true, Name = "Botswana", Alpha2 = "BW", Alpha3 = "BWA" },
    new Country { IsInUse = true, Name = "Lesotho", Alpha2 = "LS", Alpha3 = "LSO" },
    new Country { IsInUse = true, Name = "Mozambique", Alpha2 = "MZ", Alpha3 = "MOZ" },
    new Country { IsInUse = true, Name = "South Africa", Alpha2 = "ZA", Alpha3 = "ZAF" },
    new Country { IsInUse = true, Name = "Swaziland", Alpha2 = "SZ", Alpha3 = "SWZ" },
    new Country { IsInUse = true, Name = "Zimbabwe", Alpha2 = "ZW", Alpha3 = "ZWE" }
);
Country za = context.Countries.Where(x => x.Name == "South Africa").First();

I need to get the South Africa country object to perform the rest of the steps (not shown).

If I use FirstOrDefault or SingleOrDefault the system returns a null, which breaks the rest of the steps.

Why is my context returning null when I clearly added the data.

I have tried SaveChanges, but that causes other errors.

Thanks

1
Not an answer but you can re-write context.Countries.Where(x => x.Name == "South Africa").First(); as context.Countries.Single(x => x.Name == "South Africa"); - Steve
What errors do you get on SaveChanges()? Also, you can query your Local entities with context.Countries.Local.Where(... - user604613
@UrbanEsc, I get "Validation failed for one or more entities. See 'EntityValidationErrors' property for more details."...And on much deeper investigation this lead me to a MaxLenth(2) which should be MaxLength(3). Thanks. - Atron Seige

1 Answers

4
votes

you'll need to call SaveChanges() to apply the changes to the database. Until you do that, nothing is actually being written.

context.SaveChanges();
Country za = context.Countries.Where(x => x.Name == "South Africa").First();

If SaveChanges() is throwing an error, then that's your real problem, and you should post that.