除非逐步使用断点,否则代码行不起作用

She*_*115 8 c# entity-framework entity-framework-6

我唯一能想到的是竞争条件,但是调用函数和代码行与我的知识是同步的.

/// <summary>
/// Gets the log format string for an info-level log.
/// </summary>
public static string Info<T>(string action, T obj)
{
    var stringBuilder = new StringBuilder(String.Format(
        "Action: {0} \tObject: {1} \tUser: {2} \tJson: ",
        action, typeof(T).Name, User
    ));

    // Set all virtual properties to null. This should stop circular references of navigation properties.
    var virtualProperties = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(x => x.GetSetMethod().IsVirtual && !x.PropertyType.IsPrimitive);
    foreach (var propInfo in virtualProperties)
    {
        propInfo.SetValue(obj, null); // This Line is the culprit.
    }

    GetJsonSerializer().Serialize(obj, stringBuilder);

    return stringBuilder.ToString();
}
Run Code Online (Sandbox Code Playgroud)

该生产线propInfo.SetValue(obj, null)如果我只是循环和步骤之前通过一个接一个(或在该行刚刚突破),但是如果我不使用断点它从来没有设置该属性(IES)为null断点将被执行.为什么是这样?

具体细节:

  • 如果我不使用断点,它就不起作用.
  • 如果我在foreach的顶部放置一个断点并点击f5则不起作用.
  • 如果我在foreach的顶部放置一个断点并通过f10逐步执行它确实有效.
  • 如果我在代码行上放置一个断点,propInfo.SetValue(obj, null);它确实有效.
  • 循环后的断点仍然显示值为非null.
  • 如果我null改为5(这不是一个有效值),它会抛出一个异常,告诉我它不是一个有效值.

澄清一下,"不起作用"意味着它不会将该属性设置为null.

我尝试过的:

  • 重新启动Visual Studio(2013)
  • 更改代码行(以前是default(T))
  • 项目属性 - >构建 - >优化代码(最初关闭)

编辑

已经缩小了EF导航属性是导致这种行为的原因.代码正在运行但由于某种原因导航属性拒绝变为null.那么导航属性会导致这种行为呢?

She*_*115 5

延迟加载

导航属性是延迟加载的,所以当序列化程序查看它们时,它们会被原始值覆盖.所以null的设置一直在工作,但是被延迟加载覆盖了.

调试

调试出现的原因是因为我在执行SetValue代码行之前查看了该值.这导致导航属性在执行代码行之前加载值,导致空值不被覆盖.

foreach (var propInfo in virtualProperties)
{
    propInfo.GetValue(obj); // Trigger any navigation property to load.
    propInfo.SetValue(obj, null);
}
Run Code Online (Sandbox Code Playgroud)