简体   繁体   中英

Adding List Items to an Entity Framework Context from a Nested List

I am trying to insert some records into a database using Entity Framework. What I am struggling with is accessing the properties of the internal lists.

The inner lists have the following structure:

 public class Innerlist { public string item1 { get; set; } public List<string> item2 { get; set; } public List<object> item3 { get; set; } public int item4 {get; set;} etc... } 

The above list is then wrapped in another list. My question is how do I access the properties Item1, Item2, and Item3?

My looping code has the following structure:

using(var context = new fooContext())
{
    foreach (var innerList in Outerlist)
    {         
        try
        {
            context.fooEntity.Add(innerList);
        }
        catch (Exception ex)
        {
            Console.WriteLine("\n\n" + ex);
            Console.ReadLine();
        }
    }
}

I tried using a foreach loop that looped through the outer list and then another to loop through the inner list. This however generated an error about the class not containing a public definition of 'GetEnumerator'.

The inner foreach loop is structured like this:

   foreach (var innerList in outerList)
{
    foreach(var item in innerList)
    {
        try
        {
            context.fooEntity.Add(item);
        }
        catch (Exception ex)
        {
            Console.WriteLine("\n\n" + ex);
            Console.ReadLine();
        }
    }

}

I am now getting the errors: 'The best overloaded match has some invalid arguments.' And 'Cannot convert from object to InnerList Class.'

EDIT

I should add that this is being converted into a list using JSON.net which is taking a JSON string and converting it into a list via the innerList class, which exists as Entity Framework Model class.

Any help would be great. Cheers.

Your Innerlist class is not a list. It is a class that contain a list. Make your Innerlist object implement IEnumerable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM