views:

114

answers:

2

Hey everyone,

I'm trying to retrieve a single entity from a Linq2Sql query, but I'm having trouble finding the 'pretty' way of doing it. Here's what I've found that works:

 var states = from state in dc.States where state.Id == j.StateId select state;
State s = states.ToList<State>().ToList()[0];

I'm hoping this isn't the best way of getting the entity. :-P

Anyone have a better solution?

Thanks in advance!

--J

+4  A: 

try this:

int stateID = getTheStateIDToLookup();    
State state = dc.States.SingleOrDefault(s => s.StateID == stateID);
Bramha Ghosh
I love this community. You guys rock.
Joel.Cogley
+2  A: 
var s = dc.States
    .SingleOrDefault(st => st.Id == j.StateId);

Also keep in mind that this requires that there by only one state which matches your criteria, which is probably true in your case. Or you could use:

var s = dc.States
    .FirstOrDefault(st => st.Id == j.StateId);

Or you could get rid of the OrDefault like so if you KNOW there is a state which matches your criteria:

var s = dc.States
    .Single(st => st.Id == j.StateId);
Dave Markle