【问题标题】:Linq To Entities Result In ViewBag Throws ExceptionLinq To Entities 导致 ViewBag 引发异常
【发布时间】:2013-07-02 07:42:10
【问题描述】:

如果您阅读此问题,请注意调试器可能指向与实际错误所在行不同的行,请查看我的答案。

我的控制器中有以下内容:

(1) ViewBag.AppointmentSlot = context.AppointmentSlots.Where(s => s.ID == id).Single();

在我看来,我会这样做:

(2) @ViewBag.AppointmentSlot.Day.Add(ViewBag.AppointmentSlot.StartTime).ToString()

它在上面的行(2)中抛出以下异常:

Cannot perform runtime binding on a null reference
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot perform runtime binding on a null reference

感谢您的帮助。


编辑:

AppointmentSlot.Day 的类型为 DateTime

AppointmentSlot.StartTime 的类型为 TimeSpan


编辑2:

我可以在调试期间访问 ViewBag 属性,ViewBag.AppointmentSlot 不是null 在引发上述异常时。

我试图强制 LINQ To Entities 急切加载 AppointmentSlot,但没有成功:

ViewBag.AppointmentSlot = context.AppointmentSlots.Where(s => s.ID == id).ToList().Single();
ViewBag.AppointmentSlot = context.AppointmentSlots.Where(s => s.ID == id).ToList()[0];

两者都导致 DynamicProxy 类型(延迟加载)。


编辑 3:

对于那些可能想知道的人:我不会从控制器操作重定向到另一个视图,我只是 return View()


【问题讨论】:

  • 你调试了吗? ViewBag.AppointmentSlot 值是什么?如果为 null,您应该在 if statement 中检查它
  • @AliRızaAdıyahşi 查看我的编辑。

标签: c# .net asp.net-mvc entity-framework linq-to-entities


【解决方案1】:

确保ViewBag.AppointmentSlot 不为空:

if (ViewBag.AppointmentSlot != null) {
    @ViewBag.AppointmentSlot.Day.Add(ViewBag.AppointmentSlot.StartTime).ToString()
}

【讨论】:

    【解决方案2】:
      @ViewBag.AppointmentSlot.Day.Add(ViewBag.AppointmentSlot.StartTime).ToString()
    </div>
    <p>
      ...
    </p>
    --> <input type="hidden" name="AppointmentSlotID" value="@ViewBag.AppointmetnSlot.ID" />
    

    调试器显示错误的行。问题是以下内容输入错误:value="@ViewBag.AppointmetnSlot.ID"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多