Search code examples
asp.netsql-serverasp.net-identity

Get all columns by eager loading


I created a table with relation with ApplicationUser and when I want to get with eager-loading, I could not get all columns from that table my search base on user authentication.

var UserSites = await _SqldbContext.Users
                                   .Where(x => x.UserName == User.Identity.Name)
                                   .Include(x => x.sites)
                                   .ToListAsync() ;
return Json(UserSites);

But in return I only get one row of that table with two columns

[{"sites":[{"id":1,"userId":"c0e8be95-535c-449c-9aa1-06702cd4c983"

but I have more rows with this userId and also here I get only two columns but I have more than two columns, I am not sure what is wrong here please help me.


Solution

  • I think ToListAsync() works properly and If you make break point you may see all data from your site but here I think Json does not show it properly, instead of start from User table in your example I started with your proposed table name sites (to get all data of this table)

     var UserSites = await _SqldbContext.sites.Include(x => x.[Name Of User in relation table]).Where(y=>y.[Name Of User in relation table].UserName== User.Identity.Name)
                    .ToListAsync();
    
    
            List<sites> siteObject=new List<sites>();
    
            UserSites.ForEach(x =>
            {
                sites site = new sites() {
                // fill property of your class
                };
    
                siteObject.Add(site);
            });
    
    
            return Json(siteObject);
    

    I hope this code works for you.