actionresult上的invalidoperationexception

时间:2016-06-21 07:15:58

标签: c# asp.net-mvc-4 actionresult

我试图将三个数据库表中的一些数据放入视图中。因此,我使用一个类,其中包含另外两个带List的类。

这两个包含的类中的一个工作正常,但另一个在控制器ActionResult中导致InvalidOperationException。

这是我迄今为止制作的:

namespace ArrangeAppointments.Models
{
    public class Appointment : IAppointment
    {
        #region Implementation of IAppointments
            public int UserId { get; set; }
            public string Title { get; set; }
            public string Description { get; set; }
            public string Duration { get; set; }
            public virtual List<Invitee> Invitees { get; set; }
            public virtual List<Occasion> Occasions { get; set; }
        #endregion
        public int AppointmentId { get; set; }


namespace ArrangeAppointments.Models
{
    public class Invitee : IInvitee
    {
        public int Id { get; set; }
        public int AppointmentId { get; set; }
        public string Email { get; set; }
        public string Presence { get; set; }
        public virtual Appointment Appointment { get; set; }


namespace ArrangeAppointments.Models
{
    public class Occasion : IOccasion
    {
        public int Id { get; set; }
        public int AppointmentId { get; set; }
        public DateTime ocDate { get; set; }
        public DateTime ocTime { get; set; }
        public string Location { get; set; }
        public virtual Appointment Appointment { get; set; }

的ActionResult

[HttpGet]
public ActionResult NewApp(int Id)
{
    if (Id == 0)
    {
        return View();
    } else {
        try
        {
            using (var db = new MainDbContext())
            {
                Appointment appointment = db.Appointments.Find(Id);
                if (appointment == null)
                {
                    return HttpNotFound();
                }
                else
                {
                    return View("NewApp", appointment);
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            Console.WriteLine(e.InnerException);
            return View();
        }
    }
}

对象&#39;约会&#39;在ActionResult中填充了除List for Occasion之外的所有必需数据。这会导致异常。 但是,此异常不会触发catch事件。

导致此例外的原因是什么?

DbContext类

namespace ArrangeAppointments
{
    public class MainDbContext : DbContext
    {
        public MainDbContext() : base("name=DefaultConnection")
        {
        }

        public DbSet<User> Users { get; set; }

        public DbSet<Appointment> Appointments { get; set; }

        public DbSet<Invitee> Invitees { get; set; }

        public DbSet<Occasion> Occasions { get; set; }
    }
}

1 个答案:

答案 0 :(得分:0)

您需要包含列表

 Appointment appointment = db.Appointments.include("Occasions").include("Invitees").SingleOrDefault(a => a.AppointmentId == Id);