【问题标题】:Property 'Int32 Year' is not defined for type 'System.Nullable`1[System.DateTime]' When comparing year in two dates在比较两个日期中的年份时,未为类型“System.Nullable`1[System.DateTime]”定义属性“Int32 Year”
【发布时间】:2017-12-30 06:07:37
【问题描述】:

比较日期时间中的年份时出现奇怪的异常。

示例代码:

_dbContext.Details.Where(x => x.Person.Birth.Year == date.Year);

Birth 和 date 都不能为空的 DateTime。

异常信息:

Message: System.ArgumentException : Property 'Int32 Year' is not defined for type 'System.Nullable`1[System.DateTime]'

我尝试在内存中设置数据库的情况下运行单元测试中的代码。

【问题讨论】:

  • Birthdate的类型有哪些?
  • Person.Birth.Value.Year
  • 它不能为空。在下面发布答案。

标签: c# entity-framework entity-framework-core


【解决方案1】:

如果可以为空,则需要访问:

date.Value.Year

【讨论】:

  • 显然,当date 为空时产生 NRE。
【解决方案2】:

所以,您似乎有“日期时间”?而不是“日期时间”。这样,您必须检查类似的内容:

_dbContext.Details.Where(x => date.HasValue && (x.Person.Birth.Year == date.Value.Year));

【讨论】:

    【解决方案3】:

    我的模型定义错误,我没有正确指定外键。

    看起来类似(从PerId 重命名为PersonId 后问题消失了):

    public class Person
    {
        public int Id {get; set;}
        public DateTime Birth {get; set;}
    }
    
    public class Details 
    {
        public int Id {get; set;}
        public int PerId {get; set;}
        public Person Person {get; set;}
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多