Search code examples
c#linq-to-sqlargumentnullexception

Need solution for troubled null problem


For a day now i'm stuck with this null problem in my repository. here is my piece of code writen for linq to sql... i've tried a lot of options but no help for this.

the problem here is if the vidList got null value, it got stuck right in 3rd line.

if the vidList is ok, but the fidListE got null, it will stil cause null exception in the return.

I tried quite a lot of options like use Count, use '??' ... but still no help.

    public List<ATTACHMENT> existedAttachment(IList<int> vidList, IList<int> fidList, IList<int> iidList)
    {
        IEnumerable<int> vidListE =  vidList.Distinct();
        IEnumerable<int> fidListE = (fidList != null) ? fidList.Distinct() : null;
        IEnumerable<int> iidListE = (iidList != null) ? iidList.Distinct() : null;
        return (from d in _db.ATTACHMENTs
                   .Where<ATTACHMENT>(d =>
                       ((vidListE != null) ? (vidListE.Contains<int>(d.VID_ID.Value)) : false) ||
                       ((fidListE != null) ? (fidListE.Contains<int>(d.FID.Value))    : false) ||
                       ((iidListE != null) ? (iidListE.Contains<int>(d.IMG_ID.Value)) : false)
                    )
                select d).ToList<ATTACHMENT>();
    }

can some one please provide me a little clue. Thank you very much. my brain just stuck with newyear. :P


Solution

  • Instead of using null, use the built-in Empty enumerable:

    IEnumerable<int> fidListE = (fidList != null) ? fidList.Distinct() : Enumerable.Empty<int>();
    

    The Contains() method now always returns false and you don't have to check for null in the query.