Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在比较两个日期中的年份时,未为类型“System.Null”“1[System.DateTime]”定义属性“Int32 Year”_C#_Entity Framework_Entity Framework Core - Fatal编程技术网

C# 在比较两个日期中的年份时,未为类型“System.Null”“1[System.DateTime]”定义属性“Int32 Year”

C# 在比较两个日期中的年份时,未为类型“System.Null”“1[System.DateTime]”定义属性“Int32 Year”,c#,entity-framework,entity-framework-core,C#,Entity Framework,Entity Framework Core,我在用日期时间比较年份时遇到了一个奇怪的例外 示例代码: _dbContext.Details.Where(x => x.Person.Birth.Year == date.Year); 其中出生日期和日期都不可为空DateTime 异常消息: 消息:System.ArgumentException:未为类型“System.Nullable`1[System.DateTime]”定义属性“Int32 Year” 我试图在内存中设置数据库的情况下运行单元测试中的代码。我的模型定义错误,并且

我在用日期时间比较年份时遇到了一个奇怪的例外

示例代码:

_dbContext.Details.Where(x => x.Person.Birth.Year == date.Year);
其中出生日期和日期都不可为空DateTime

异常消息:

消息:System.ArgumentException:未为类型“System.Nullable`1[System.DateTime]”定义属性“Int32 Year”


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

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

它看起来类似于从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;}
}

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

date.Value.Year

看来你有约会时间了?而不是日期时间。这样,您必须检查以下内容:

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

出生和日期的类型是什么?Person.Birth.Value.year不可为空。下面贴出答案。显然,当日期为空时,收益率为NRE。