Home > Enterprise >  Working with list of objects in net core MVC
Working with list of objects in net core MVC

Time:04-03

I have a some questions about utilizing lists in models.

In short: I have model User which inherits from IdentityUser. There is some extra fields and a list of objects(lets say list of childs) so

public List<Child> Childs

Now i don't know how lists are stored in database, are they tho? There is no column Childs. Is it used only to store data taken from DB?

My problem is that i don't know how to work with it. Lets say i want to display all childs from logged user. Do i loop through all childs, find which have users id, move it to list and then foreach loop it? Or i should access directly Childs list without taking data from DB first? But then what happens if i change data of some childs? Lets say i added 2 childs to 1 user, later change data of single child, that way data of this child won't change in list and i need to change it in every list? I believe that's not how it's handled.

Hope i can get some explanations on lists.

CodePudding user response:

Now I don't know how lists are stored in database, are they tho? There is no column Childs. Is it used only to store data taken from DB?

Usually records are sored in separate table, for example UserChild, which has reference to parent table

Lets say I want to display all Childs from logged user.

var allChildren = ctx.Users
   .Where(u => u.Id == userId)
   .SelectMany(u => u.Childs)
   .ToList();

But then what happens if I change data of some childs? Lets say I added 2 childs to 1 user, later change data of single child, that way data of this child won't change in list and i need to change it in every list? I believe that's not how it's handled.

Changes should be recorded in appropriate table and query above should get updated data from Database.

Probably before starting doing something, you should read EF Core documentation.

  • Related