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?
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);
}
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;