Entity Framework Select Row

c# entity-framework

Question

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:

Database: ItemSchema contains Defindex, Name, MarketPrice

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.

1
0
12/16/2013 6:10:46 PM

Popular Answer

You can use FirstOrDefault or SingleOrDefault (if there should be no more than one row matching your Defindex value) to get single row from table:

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.

2
12/16/2013 6:18:24 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow