Entity Framework CodeFirst Calling Find does Top 2
While using ADO.NET Entity Frameworkâs CodeFirst and we call Find() method against the PrimaryKey field we get one record. But surprisingly if we dig deeper we will be able to see that it is calling Top 2 which means actually getting two rows.
Why is it so? Because just to track if there are more than one record in the field it will throw an error. Now the question is why is it possible to have duplicate record in the Primary Key value? Scenario could be, it may have the model created and later the database column was modified so it is no more primary/unique anymore.
Below is the generated query for
private static void SelectSingleEmployee(int id)
{
using (var ctx = new HRContext())
{
Console.WriteLine(ctx.Emps.Find(id).EmpName);
}
}
exec sp_executesql N'SELECT TOP (2)
[Extent1].[EmpId] AS [EmpId],
[Extent1].[EmpName] AS [EmpName]
FROM [dbo].[Emps] AS [Extent1]
WHERE [Extent1].[EmpId] = @p0',N'@p0 int',@p0=1
Namoskar!!!