0
votes

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. - user2864740

1 Answers

1
votes

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"},
        };
   }