0

When I'm looking for a record that is mapped to an object model, I have something like this:

var Output = (from x in MyDC.SomeTable
              where  ....
              select new SomeObjectModel()
              {
                 SomeProp = x.SomeColumnField

              }.Single();

Now, I want to return on object but only if the object was found I'm doing this:

var Output = (from x in MyDC.SomeTable
              where ....
              orderby x.SomeTime descending
              select s).FirstOrDefault();

This tells me if the object was found and from there, I want to be able to retrieve SomeObjectModel() and fill in its properties but only if there's an element that was found with the .FirstOrDefault() statement and combine all this into one query. I tried adding a Select after .FirstOrDefault() but it doesn't work.

Thanks for your help.

1
  • Define "doesn't work" please; what happens? This should just be a cause of replacing Single with FirstOrDefault... Commented Nov 21, 2013 at 14:33

2 Answers 2

3

Use FirstOrDefault with your first version. You can also use SingleOrDefault if you are expecting only a single item or null.

var Output = (from x in MyDC.SomeTable
              where  ....
              select new SomeObjectModel()
              {
                 SomeProp = x.SomeColumnField

              }.SingleOrDefault(); //if only single item is expected or null

return Output;
Sign up to request clarification or add additional context in comments.

5 Comments

In the query, I'm sorting all the returns of the where clause and I'm sorting them by descending to take the top one. If I add the orderby statement after the where clause, is this going to return the object based on the latest record in the DB?
OrderBy would return the items in ascending order, if you are trying to get latest records then I believe you need OrderByDescending on some DateTime type field.
I have orderby x.SomeDateTime descending
@frenchie, that should work, but are you expecting single or multiple records against your condition in where clause, if you are expecting single then use SingleOrDefault, if you are expecting multiple and want to get the first one then use FirstOrDefault
Thanks, caught that: changed it to FirstOrDefault!
1
var OutputAsModel = (from x in MyDC.SomeTable
where ....
orderby x.SomeTime descending
select s).Select(o=>new SomeObjectModel(o)).FirstOrDefault();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.