Thomas Koelle
Thomas Koelle

Reputation: 3742

Entity framework core does not include when ToListAsync, but does with FirstOrDefaultAsync

I have a query that looks like this (Entity framework core 2.2.7):

        var query = from row in _entities.MyEntities
                .Include(e => e.MyEntityChildren)
                .Include(e => e.MyParent)
                .Include(e => e.MyParent2)
                .Include(e => e.MyParent3)
                .Include(e => e.MyParent4)
            where row.MyParent4.Id == "whatever" &&
                  dict.Contains(row.Id) &&
                  active.Contains(row.Status)
            select row;

Then I have different results based on how I execute the query:

var e = await query.FirstOrDefaultAsync();

Works correct

var e = await query.Distinct().ToListAsync();

Does not populate MyParent3. But both queries include all the other relations.

So my question is. Is this a known issue? What is the difference between first and list? And does anything know how to resolve it?

The generated sql looks the same and MyParent3 is fetched from database in both cases so I suspect it is something with the serializer. This worked in entity framework core 2.0.9

EDIT:forgot distinct!

Upvotes: 1

Views: 1430

Answers (2)

Thomas Koelle
Thomas Koelle

Reputation: 3742

I have no idea why it happens and also don't really want to post the whole project because MyEntity is e.g. Orders and MyParent3 is ShippingInformation

But, if I loop the result like this it works:

var result = new List<MyDomainEntity>();
foreach (var dto in query.Distinct())
{
    result.Add(GetEntity(dto));
}

I will just leave the result if anyone else experience this.

EDIT: I had made a naming conflict.

Upvotes: 1

Joseph
Joseph

Reputation: 467

Difference between first and list assuming data of (2, 3, 4, 1) from your query:
- Lists is similar to an array, which contains more than 1 element will get ([2, 3, 4, 1])
- First only contains 1 element, which is the first element (2)

As to why it is not working, my best guess is:
1. The format of the data obtained through your query is not able to serialize into a list, therefore there is no output there.
2. Your first example does not have the actual data too, which will return a default item

Upvotes: 1

Related Questions