gpt4 book ai didi

asp.net-mvc-3 - LINQ的* OrDefault在MVC3 + ActiveRecord中引发异常

转载 作者:行者123 更新时间:2023-12-02 04:00:05 25 4
gpt4 key购买 nike

this question的刺激下,我决定在MVC3 / ActiveRecord应用程序中尝试此操作。

我已经有很多模型在工作,并且有一些 View 可以处理这些模型。这里没什么特别的。我的一种模型称为AppSession

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

没用我仍然收到InvalidOperationExceptionFirstOrDefaultSingleOrDefault确实如此。我最终将通话包装在try/catch中以解决该问题。

我在这里做错了什么?

编辑:根据要求,实际代码为:

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模式(以及类的属性)包括:
  • ID(int,不为null)
  • StartDate(DateTime,不为null)
  • EndDate(DateTime,空)
  • Ip(字符串,不为空)
  • MacAddress(字符串,不为null)
  • 平台(字符串,不为null)
  • 版本(字符串,不为null)
  • 最佳答案

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

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

    关于asp.net-mvc-3 - LINQ的* OrDefault在MVC3 + ActiveRecord中引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10921701/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com