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).ToLi开发者_如何学运维st<ATTACHMENT>();
}
can some one please provide me a little clue. Thank you very much. my brain just stuck with newyear. :P
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.
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>();
Should the list not be made up of nullable ints i.e
精彩评论