Populate MVC Model based on info from related table

Posts   
 
    
larkydoo
User
Posts: 45
Joined: 30-Jun-2008
# Posted on: 28-Nov-2016 23:49:02   

I'm populating my MVC ViewModel by iterating through my LLBLGen collection and adding to the model in each loop. Here's my code:

            
foreach (OrganizationEntity myEntity in Organizations)
            {
                myOrgs.Add(new OrganizationViewModel
                {
                    City = myEntity.City,
                    State = myEntity.State,
                    OrganizationName = myEntity.OrganizationName,
                    IsApproved = myEntity.IsApproved,
                    Website = myEntity.Website,
                    IsOrphan = myEntity.Resources.Count > 0, 
                    FriendlyPath = myEntity.FriendlyPath
                });
            }

The problem I'm coming across is that the setting of IsOrphan relies on counting the number of related Resource records. If 0, IsOrphan is true, else it is false. This is not the most efficient way of doing things as, each time it iterates through the loop, it has to call the database to determine how many related resources there are. It takes around 2-3 seconds on my local machine and as the number of "Organizations" includes, that time will just increase as well.

Is there a better way for me to do this?

Using LLBLGen 4.2 right now.

daelmo avatar
daelmo
Support Team
Posts: 8245
Joined: 28-Nov-2005
# Posted on: 29-Nov-2016 07:07:14   

Yes, for this particular scenario where you don't really need the associated 1:n collection but only the count of them, I would recommend using a DynamicList.

Also, if you use QuerySpec or Linq2LLBL you can project the results directly into your POCO.

David Elizondo | LLBLGen Support Team
larkydoo
User
Posts: 45
Joined: 30-Jun-2008
# Posted on: 29-Nov-2016 21:00:27   

Thanks, that worked. Went from roughly 2 seconds to 200 ms.