If a LINQ to Entities query produces no results, how do you deliver a default value?

defaultifempty entity-framework linq linq-to-entities

Question

In a LINQ to entities expression like this:

var vote = (from vote in db.Vote where
    vote.Voter.Id == user.Id
    select v).FirstOrDefault();

How do you add a DefaultIfEmpty value so that when there's no vote I'd get a default value?

1
11
5/16/2011 6:06:05 AM

Accepted Answer

I ended up going for a very simple approach which was recommended by an answer here that was latter erased:

var vote = (from vote in db.Vote 
            where vote.Voter.Id == user.Id
            select v).FirstOrDefault();
if (vote == null) {
    vote = new Vote() { .... };
    db.AddToVoteSet(vote);
}
1
8/24/2009 9:01:35 AM

Popular Answer

Another approach, if Vote is a reference type and thus uses null as its default value, would be to use the null coalescing operator:

var vote = (db.Vote
   .Where(v => v.Voter.Id == user.Id)
   .FirstOrDefault()) ?? defaultVote;


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow