Psyfun
Psyfun

Reputation: 369

Why does this Entity Framework LINQ query fail?

I have a simple EF Linq query that used to work. Now it is returning null every time and I can't track down why.

public Sample GetDataSample(Equipment equip)
{
    Sample sample = null;
    try
    {
        sample = this.Samples.FirstOrDefault(s => s.EquipmentId == equip.Id);
    }
    catch (Exception e)
    {
        // do nothing for now
    }
    return sample;
}

This is called from within an active DbContext with a valid Equipment entity. Here is what I am seeing in the debugger. I have verified that the DbSet Samples in the active context does contain data that should match. Please tell me I am missing something obvious.

enter image description here enter image description here

EDIT: I did a LINQ profile to see what the SQL generated was and it looks fine:

SELECT TOP (1) 
[Extent1].[Id] AS [Id], 
[Extent1].[EquipmentId] AS [EquipmentId], 
[Extent1].[SampleTime] AS [SampleTime]
FROM [Pbhs].[Samples] AS [Extent1]
WHERE [Extent1].[EquipmentId] = 1

Now, I am wondering if the EF lookup is checking the local proxy or if it is looking in the database. The data exists in the current context but has not been committed to the database yet.

Upvotes: 0

Views: 320

Answers (1)

ΩmegaMan
ΩmegaMan

Reputation: 31616

There are two things here:

 s.EquipmentId == equip.Id

How is an equipment Id, "EquipmentId" the same as a primary key Id? Are you sure you are not comparing "apples" to "oranges"?

The data exists in the current context but has not been committed to the database yet.

Then searching on Id will fail because the new item has not been committed to the database and assigned an Id.

Upvotes: 1

Related Questions