When querying a collection using linq it always returns a null
When querying a collection using linq it always returns a null
Collection<JCTransLabour> oJCTransLabours = null;
oJCTransLabour = HttpContext.Current.Session["CurrentLabourTransactions"] as
Collection<JCTransLabour>;
// at this point the collection oJCTransLabours contains 3500 records
var oCurrentLabourTrans = from clt in oJCTransLabours
where clt.TransactionDate.Date != DateTime.Now.Date
select clt;
// at this point the coll开发者_StackOverflow中文版ection oJCTransLabour = null
// I have tried to search on different fields
return oCurrentLabourTrans;
There must be something I am doing wrong. Any help would be very much appreciated.
There's at least one typo in your question.
You state that after
oJCTransLabour = HttpContext.Current.Session["CurrentLabourTransactions"] as Collection<JCTransLabour>;
oJCTransLabour
is not null, right? This makes sense if session contains it.
Then you define oCurrentLabourTrans
and assign LINQ query to it. And then you say that
// at this point the collection oJCTransLabour = null
Wait, how can it be null? You didn't even modify it (it was oCurrentLabourTrans
modified) and you just said oJCTransLabour
is not null!
Update: I just noticed there's type in names too: you call it oJCTransLabours
, then you call it oJCTransLabour
. Please post the exact code so we don't make assumptions about what exactly you might've mistyped.
And, of course, LINQ expression can't be null.
I think it is most likely that oJCTransLabours
is null though you state the otherwise.
The reason you think so, perhaps, is because you're sure HttpContext.Current.Session["CurrentLabourTransactions"]
is not null. This is true, but you use as
operator to cast the value to Collection<JCTransLabour>
. As opposed to casting operator, as
doesn't throw an exception if types mismatch, it just returns null
.
You might want to try
oJCTransLabour = (Collection<JCTransLabour>)HttpContext.Current.Session["CurrentLabourTransactions"];
and see if any errors show up.
I think you are just confusing variable names:
// You were missing an 's' before
oJCTransLabours = HttpContext.Current.Session["CurrentLabourTransactions"]
as Collection<JCTransLabour>;
This doesn't look like a linq issue, but rather that the value in the session is either null or not a Collection<JCTransLabour>
.
You could ensure it is not null by changing the lookup to:
oJCTransLabour = (HttpContext.Current.Session["CurrentLabourTransactions"] as Collection<JCTransLabour>) ?? new Collection<JCTransLabour>();
If there should always be a session value then you could throw an exception if the value was not found before doing the query.
try this:
var oCurrentLabourTrans = (from clt in oJCTransLabours where clt.TransactionDate.Date != DateTime.Now.Date select clt).ToList();
精彩评论