0

I have a SubCategory model in an mvc 4 application for a shirt shop and I am wanting to populate the database using seed data when I ran my application, I recieve Error Message: "Sequence Contains no matching elements"

My code:

    var subCategories = new List<SubCategory>
        {
    new SubCategory{Category = categories.Single(s => s.Name == "Animals") , Name "Animal Prints"},
    new SubCategory{Category = categories.Single(s => s.Name == "Animals") , Name = "Bugs"},
        };
1
  • categories.Single(s => s.Name == "Animals") - there was no category with the name "Animals". While you could use SingleOrDefault, that might end up with a NullReferenceException (or incorrect category tree) later - might want to ensure that the category exists, and/or find out why it doesn't. Jun 12, 2014 at 3:05

1 Answer 1

1

The reason is that you don't have any entry in you categories with name as "Animals" if you wanted to check it

   var categorie = categories.where(s => s.Name == "Animals").SingleOrDefault();

   if(categories == null)
   {
     // db is not seeded with categories do something
   }
   else
   {     

        var subCategories = new List<SubCategory>
        {
           new SubCategory{Category = categorie  , Name "Animal Prints"},
           new SubCategory{Category = categorie  , Name = "Bugs"},
        };
   }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.