LINQ的* OrDefault在MVC3 + ActiveRecord中引发异常 [英] LINQ's *OrDefault throws exceptions in MVC3 + ActiveRecord

查看:83
本文介绍了LINQ的* OrDefault在MVC3 + ActiveRecord中引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

提出来,我决定在我的MVC3/ActiveRecord应用程序中尝试此操作.

Spurred on by this question, I decided to try this in my MVC3/ActiveRecord application.

我已经有很多模型可以使用了,还有一些可以处理这些模型的视图.这里没什么特别的.我的一个模型称为AppSession.

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.

基于上述问题,我希望它能够正常工作:AppSession.FirstOrDefault(a => ...) ?? null.

Based on said question, I expected this to work: AppSession.FirstOrDefault(a => ...) ?? null.

它没有用.我仍然得到一个InvalidOperationException. FirstOrDefaultSingleOrDefault都是如此.我最终将通话包裹在try/catch中以解决该问题.

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.

我在做什么错了?

根据要求,实际代码为:

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

ipmacAddressplatformversion都是可验证为非null的方法变量.我的AppSessions模式(以及相应的类属性)包括:

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,不为null)
  • StartDate(日期时间,不为null)
  • EndDate(DateTime,空)
  • Ip(字符串,不为null)
  • MacAddress(字符串,不为null)
  • 平台(字符串,不为null)
  • 版本(字符串,不为null)

推荐答案

也许您的project.AppSessions本身为空?这将导致FirstOrDefault()方法引发错误.您可能想在调用FirstOrDefault之前检查它是否为null,如果它为null,则创建一个新的AppSession对象:

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

这篇关于LINQ的* OrDefault在MVC3 + ActiveRecord中引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆