LINQ's *OrDefault throws exceptions in MVC3 + ActiveRecord
-
13-06-2021 - |
Question
Spurred on by this question, I decided to try this in my MVC3/ActiveRecord application.
I have a bunch of models already working, and some views that do stuff with those models. Nothing special here. One of my models is called AppSession
.
Based on said question, I expected this to work: AppSession.FirstOrDefault(a => ...) ?? null
.
It didn't work. I still get an InvalidOperationException
. This is true of FirstOrDefault
and SingleOrDefault
. I ended up wrapping my call in try/catch
to get around it.
What am I doing wrong here?
Edit: As requested, the actual code is:
void getAnAppSession() {
AppSession sessions = project.AppSessions.FirstOrDefault(a => a.Ip == ip && a.MacAddress == macAddress && a.Platform == platform && a.Version == version && a.EndTime == null)
}
ip
, macAddress
, platform
, and version
are all method variables that are verifiably not null. My schema for AppSessions
(and accordingly, properties on my class) includes:
- ID (int, not null)
- StartDate (DateTime, not null)
- EndDate (DateTime, null)
- Ip (string, not null)
- MacAddress (string, not null)
- Platform (string, not null)
- Version (string, not null)
Solution
Maybe your project.AppSessions
itself is null? That would cause the FirstOrDefault()
method to throw an error. You might want to check if that is null before calling FirstOrDefault
and create a new AppSession object if it is null:
AppSession sessions = (project.AppSessions as AppSession ?? new AppSession())
.FirstOrDefault(a => a.Ip == ip &&
a.MacAddress == macAddress &&
a.Platform == platform &&
a.Version == version &&
a.EndTime == null);