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

标签 asp.net-mvc-3 castle-activerecord

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/

    相关文章:

    asp.net - MVC 区域路由 - 带文件夹的 Controller 文件夹

    asp.net-mvc-3 - MVC3 : Set Dropdown list Selected Value

    c# - 为什么我会收到异常 "Consider using a DataContractResolver or add any types not known statically to the list of known types"

    .net - castLe activerecord 是否正在积极维护?

    NHibernate 和数据库连接故障转移?

    .net - 如何将 XMLSerializer 与包含 IList<T> 成员的 CaSTLe ActiveRecord 结合使用

    c# - 如何在 Asp.net MVC 中为文本框创建自定义 "type"属性?

    asp.net-mvc-3 - MVC3 EditorFor 动态属性(或需要解决方法)

    c# - 在 3 个实体之间创建导航属性

    c# - 使用 CaSTLe Active Record 与 Straight NHibernate 的优缺点是什么?