Oshin Bharati
Oshin Bharati

Reputation: 33

Why is using tolist() not a good approach here?

This is not a good approach here...! can anyone say why?

var dbc= new SchoolContext();
var a=dbc.Menus.ToList().Select(x=> new {
                             x.Type.Name,
                             ListOfChildmenus = x.ChildMenu.Select(cm=>cm.Name),
                             ListOfSettings = x.Settings.SelectMany(set=>set.Role)
                                         });

Upvotes: 0

Views: 246

Answers (2)

Radu Porumb
Radu Porumb

Reputation: 785

Actually Razvan's answer isn't totally accurate. What happens in your query is this:

  1. When you call ToList() the contents of the entire table get dumped into memory.

  2. When you access navigation properties such as ChildMenu and Settings a new query is generated and run for each element in that table.

If you'd done it like so:

dbc.Menus
.Select(x=> new {
    x.Type.Name,
    ListOfChildmenus = x.ChildMenu.Select(m=>m.Name),
    ListOfSettings = x.Settings.SelectMany(z=>z.Role)
})
.ToList()

your whole structure would have been generated in one query and one round trip to the database.

Also, as Alex said in his comment, it's not necessarily a bad approach. For instance if your database is under a lot of load it's sometimes better to just dump things in the web application's memory and work with them there.

Upvotes: 1

Razvan Dumitru
Razvan Dumitru

Reputation: 12482

Because when you call .ToList() or .FirstOrDefault() and so on (when you enumerate), your query will get executed.

So when you do dbc.Menus.ToList() you bring in memory from the database all your Menus, and you didn't want that.

You want to bring in memory only what you select ( the list of child menus and the list of settings ).

Relevant furter reading : http://www.codeproject.com/Articles/652556/Can-you-explain-Lazy-Loading - probably you are using lazy loading

And if you want to add a filter to your IQueryable you may read about difference between ienumerable, iqueryable http://blog.micic.ch/net/iqueryable-vs-ienumerable-vs-ihaveheadache

And some dinamic filtering https://codereview.stackexchange.com/questions/3560/is-there-a-better-way-to-do-dynamic-filtering-and-sorting-with-entity-framework

Upvotes: 5

Related Questions