frenchie
frenchie

Reputation: 51947

returning null or object in Linq-to-SQL query

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.

Upvotes: 0

Views: 112

Answers (2)

Habib
Habib

Reputation: 223287

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;

Upvotes: 3

Kaido
Kaido

Reputation: 3961

var OutputAsModel = (from x in MyDC.SomeTable
where ....
orderby x.SomeTime descending
select s).Select(o=>new SomeObjectModel(o)).FirstOrDefault();

Upvotes: 1

Related Questions