"Sequence contains no elements" error during database seed

c# entity-framework-6

Question

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
0
11/20/2014 1:11:59 PM

Accepted Answer

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.

4
11/20/2014 1:16:22 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow