繁体   English   中英

空引用异常设置实体框架属性

[英]Null reference exception setting Entity Framework property

在将不可为空的标量变量分配给实体框架域对象属性时,我们收到了不一致的空引用异常。 我了解空引用异常是什么,但我无法理解在将非空值分配给非空 EF 域对象的属性时如何获得异常引用。

域对象如下所示:

[DataContract]
[Table("Participant", Schema = "tour")]
public partial class Participant
{
    public Participant()
    {
    }
    [DataMember]
    [Key]
    public int ParticipantID { get; set; }
    ...
    public DateTime? AutopayLastAttemptedUtc { get; set; }
}

我们遇到异常的区域是:

DateTime utcNow = DateTime.UtcNow;
// The below line throws the Null Reference Exception.
participant.AutopayLastAttemptedUtc = utcNow;
ParticipantService.Update(participant);

如果我添加一些调试代码来证明变量不为空,我仍然会在同一行上得到一个异常:

DateTime utcNow = DateTime.UtcNow;
// This line proves that participant is not null and that
// AutopayLastUpdatedUtc can be read (not that that really
// matters because we only want to set it
TelemetryClient.TrackTrace("Participant", SeverityLevel.Information, new Dictionary<string, string> {
    { "ParticipantId", participant.ParticipantID.ToString() },
    { "AutopayLastUpdatedUtc", participant.AutopayLastAttemptedUtc.ToString() }
});
// The below line throws the Null Reference Exception.
participant.AutopayLastAttemptedUtc = utcNow;
ParticipantService.Update(participant);

我不明白什么可能为空

  • 参与者不能为空,因为我们在上面一行的调试代码中使用它
  • utcNow 不能为空,因为它是不可为空的类型
  • AutopayLastUpdatedUtc 是标准的 EF 设置器

请注意,我不是在问什么是空引用异常。 我在问在将非空值分配给非空对象的属性时如何可能发生空引用异常。

尽管已经检查了几种不同的方式,@MartinLiversage 是正确的,报告的行号已关闭。 该异常实际上是由后面的一行(未在示例代码中显示)抛出的,一旦我找到了有问题的行,就很容易修复。

我重现这个的测试用例是在我们的测试服务器上而不是我的开发机器上。 这是相当正常的,因为数据库是不同的,并且在我的开发数据库上找到触发相同问题的数据库记录并不总是那么容易。 不过,它确实使调试变得更加困难。 测试服务器构建时设置了“定义调试常量”,但它也设置了“优化代码”,所以我想知道这是否是导致错误报告行的原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM