Nested Forloop in asp.net core RRS feed

  • Question

  • User2041008840 posted

    i have two table 
    Country and State which is also connected to each other using FK PK. 
    I want to represent the data in this form 

    United States

    I think structure will be like this 
    Foreach (Country)

    How can i code this ? I tried but its not work by me. please tell me how can i implement this. 

    Friday, October 4, 2019 3:27 PM


All replies

  • User475983607 posted

    The first step crafting an View Model that fits represents the UI you are trying to achieve.

        public class Country
            public int Id { get; set; }
            public string Name { get; set; }
            public List<State> States { get; set; }
        public class State
            public int Id { get; set; }
            public string Name { get; set; }

    Fill the view model and display the view model.

    foreach(Country country in countries)
        //Write Country
        foreach(State state in country.States)
            //Write state
            Console.WriteLine($" {state.Name}");

    These concepts are covered in EF Core fundamentals.

    Friday, October 4, 2019 4:30 PM
  • User2041008840 posted

    its not working sir. I think i made mistake while putting code. 

    can you please tell me where do i place this ? What is 'countries' ? I got this Country is coming from ViewModel

    Please help me, I am new on .net core 

    Thank You

    Friday, October 4, 2019 6:07 PM
  • User1724605321 posted

    Hi Prathamesh shende ,

    I would suggest you first read how to enable relationship in EF Core :

    Configuring One To Many Relationships in Entity Framework Core

    So that you can read with  navigation property easily :



    Best Regards,

    Nan Yu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, October 7, 2019 5:07 AM