Reputation: 57
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.
Upvotes: 0
Views: 11304
Reputation: 236208
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.
Upvotes: 2
Reputation: 218722
var defIndex=3; //your value
var item=yourDbContext.ItemSchemas.FirstOrDefault(s=>s.DefIndex==defIndex);
if(item!=null)
{
//Record exists.Let's read the Name property value
string theName=item.Name;
// do something with theName now
}
Assuming your DBContext object has a collection(of ItemSchema) named ItemSchemas
Upvotes: 0