Answered by:
Nested Forloop in asp.net core

Question
-
User2041008840 posted
Hi,
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 formUnited States
California
NewYork
India
Delhi
PanjabI think structure will be like this
Foreach (Country)
{
Foreach(State)
}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
Answers
-
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 :
https://www.entityframeworktutorial.net/efcore/one-to-many-conventions-entity-framework-core.aspx
https://www.learnentityframeworkcore.com/conventions/one-to-many-relationship
Best Regards,
Nan Yu
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Monday, October 7, 2019 5:07 AM
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 Console.WriteLine(country.Name); 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 :
https://www.entityframeworktutorial.net/efcore/one-to-many-conventions-entity-framework-core.aspx
https://www.learnentityframeworkcore.com/conventions/one-to-many-relationship
Best Regards,
Nan Yu
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Monday, October 7, 2019 5:07 AM