Select two lists as one list in ASP.NET Core linq

asp.net-core entity-framework-core linq

Question

I am trying to create a query with ASP.NET Core EF Core and Linq that would give me a List of users based on two different lists, something like this:

return await _context.Users
            .Include(u => u.PropertyOwners)
                .ThenInclude(po => po.Property)
                    .ThenInclude(p => p.PropertyTenantLeases)
            .Include(u => u.PropertyOwners)
                .ThenInclude(po => po.Owner)
            .Where(u => u.Id == userID)
            .Select(u => new List<User>() 
            { 
                u.PropertyTenantLeases.Select(ptl => ptl.Tenant).ToList()
                u.PropertyOwners.Select(po => po.Owner).ToList() 
            }).FirstOrDefaultAsync();

The tables that are used in this query are connected in the following way: Table design Everything is fine with this query except for the Select, with the Select I am trying to achieve that it returns a list of all the tenants in the PropertyTenantLeases table which is a junction table togheter with all the Owners form the PropertyOwners junction table (both Tenant and Owner are IdentityUser classes. When I right this query like this I get the following error:

The best overloeaded Add method 'List<User>.Add(User)' for the collection initializer has some invalid arguments

and also

Argument 1: cannot convert from 'System.Collections.Generic.List<RosyMasterDBManagement.Models.User>' to 'RosyMasterDBManagement.Models.User'
1
-1
3/30/2020 8:08:20 PM

Accepted Answer

Joining two list is called a union in Linq -- I believe that is what you want:

note: I still can't test this since you gave a picture of the data model instead of the code that would allow me to be certain of how to implement. expect the fields to be named incorrectly etc.

var ownerlist = _context.Users
            .Include(u => u.PropertyOwners)
                .ThenInclude(po => po.Owner)
            .ToList();

var tenantlist = _context.Users
            .Include(u => u.PropertyOwners)
                .ThenInclude(po => po.Property)
                    .ThenInclude(p => p.PropertyTenantLeases)
                      .ThenInclude(po => po.Tenant)
            .ToList();

return ownerlist.Union(tenantlist);

I don't believe you need await() since ToList() forces it to not be lazy. But I could be wrong about that.

1
3/31/2020 4:12:00 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow