I've got these two LINQ expressions. I'm using Entity Framework. The only difference is the position of the items on the list of CardIds.
The first example returns the AdditionalCards that comes from "MemberAdditionalCards" first and then it adds the Card that is stored on the Members table.
The second example does the opposite, gets first the Card that is stored on the Members table and then the AdditionalCards that comes from "MembersAdditionalCards".
First LINQ:
members = await _context.Members
.Where(s => EF.Functions.Like(s.FirstNames, searchTerm))
.Select(s => new Members
{
Id = s.Id,
CardIds = s.MemberAdditionalCards
.Select(m => new AdditionalCard
{
CardId = m.CardId
})
.Union(new List<AdditionalCard>
{
new AdditionalCard
{
CardId = s.CardId
}
})
.ToList()
})
.AsNoTracking()
.ToListAsync();
Second LINQ:
members = await _context.Members
.Where(s => EF.Functions.Like(s.FirstNames, searchTerm))
.Select(s => new Members
{
Id = s.Id,
CardIds = new List<AdditionalCard>
{
new AdditionalCard
{
CardId = s.CardId
}
}
.Union(s.MemberAdditionalCards
.Select(a => new AdditionalCard
{
CardId = a.CardId
}))
.ToList()
})
.AsNoTracking()
.ToListAsync();
With the Second LINQ I've got an error:
The first LINQ expression works fine but is not how I want to have the items on the list result.
With the Second LINQ expression: if I remove the "await" keyword from the second expression and in the end I do ToList() rather than ToListAsync() it works just fine. I do understand the issue is the async execution. But how can I make the last bit to be executed as async and why that issue doesn't happen with the First LINQ expression?
Thanks!

It's complaining about this part:
Since you're doing a
Unionon aList<T>(which isIEnumerable), thenUnionwill only accept anIEnumerableas a parameter. Buts.MemberAdditionalCards.Select()returnsIAsyncEnumerable.I'm not sure if it will like the
awaitinside the Linq expression, so if it doesn't, then remove theawaitand changeToListAsync()toToList():I'm not sure what the resulting SQL will look like. Someone might have a better idea.