views:

39

answers:

3

Hi,

what's the shortest way of returning an Entity Framework object from one table based on it's name attribute?

So say one had a table person, with column name, what would be the quickest way to return the person object with name = "Tim" say?

e.g. context.People.Select(m => m.Name == "Tim") doesn't seem to work?

+3  A: 
context.People.First(m => m.Name == "Tim")
Vitalik
+1  A: 

Are you wanting only a single object? If you are confident there is just one item in the table that meets your criteria, you could say

context.People.Single(m => m.Name == "Tim");

If there could be more than one and you only want the first, then use the .First() extension method instead. The difference is that Single will throw an exception if more than one record matches your criteria. First simple does what it says, it will take the first of any number of records.

(Also consider the SingleOrDefault and FirstOrDefault methods if there may be no suitable records in the table.)

Edit: Apparently .Single is not supported in the Linq-To-Entities framework, but First is.

Anthony Pegram
great - probably did mean a Single even though I didn't specify it. BTW is this Linq to Entities that is being used here?
Greg
I don't think Single is implemented in Entity Framework as of .net 3.5. Maybe in 4... Didn't try yet.
Vitalik
@Vitalik - Ah, it apparently is in Linq-to-SQL but not in L2E (unless that changed with 2010). First() is supported, however. I've upvoted yours and I'll update mine.
Anthony Pegram
A: 

This works also... (maybe it's not the shortest way but I find it more readable)

        var person = (from p in context.People
         where p.Name == "Tim"
         select p).FirstOrDefault();
cepriego