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 an expression using LINQ to Entities like this:

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

How can I add a DefaultIfEmpty value so that I get a default value if there is no vote?

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

Accepted Answer

I ultimately chose a fairly straightforward strategy that was advised by a response here that was later deleted:

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

Alternatively, ifVote When a reference type and has null as its default value, the null coalescing operator should be used:

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