views:

77

answers:

3

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

A: 

Should the list not be made up of nullable ints i.e

Burt
what do you mean? :) here the list supposedly to contain 0 element if it does not have any. but instead of that, it goes directly to null, which cause the IEnumerable.Contains to struggle. I don't know of a way to get out of this problem.
DucDigital
+1  A: 

Have you tried something like this at the very beginning of the method. This sets it to an empty list if the parameter is null.

 IEnumerable<int> vidListE = (vidList != null) ? vidList.Distinct() : new List<int>();
 IEnumerable<int> fidListE = (fidList != null) ? fidList.Distinct() : new List<int>();
 IEnumerable<int> iidListE = (iidList != null) ? iidList.Distinct() : new List<int>();

return (from d in _db.ATTACHMENTs
                   .Where<ATTACHMENT>( d =>
                       vidListE.Contains<int>(d.VID_ID.Value) ||
                       fidListE.Contains<int>(d.FID.Value) ||
                       iidListE.Contains<int>(d.IMG_ID.Value) )
                    )
                select d).ToList<ATTACHMENT>();
tvanfosson
+1  A: 

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.

Hans Passant