LINQ's *OrDefault throws exceptions in MVC3 + ActiveRecord

我们两清 提交于 2019-12-12 13:25:59

问题


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)

回答1:


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);


来源:https://stackoverflow.com/questions/10921701/linqs-ordefault-throws-exceptions-in-mvc3-activerecord

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!