For some reason I can't seem to figure out how to use Entity Framework to select a single row.
Here is what I have:
I need to select the
Name based on a
Defindex I already have.
So I want to match the
Defindex with a record, and retrieve the Name from that record.
var row = context.TableName.FirstOrDefault(r => r.Defindex == value); if (row != null) // use row.Name;
If you are using default EF provider for SQL Server, then this will generate SQL query
SELECT TOP (1) [Extent1].[Defindex] AS [Defindex], [Extent1].[Name] AS [Name], [Extent1].[MarketPrice] AS [MarketPrice] FROM [dbo].[TableName] AS [Extent1] WHERE [DefIndex].[Id] > @value
Same query can be written also this way
var row = context.TableName.Where(r => r.Defindex == value) .FirstOrDefault();
SingleOrDefault will try to select top 2 results and it will throw exception if there is more than one row returned.