System.ObjectDisposedException with Virtual property in entity framework

asp.net-mvc c# entity-framework

Question

Hi can anybody help with this I am getting the above error when trying to display data about the Carmodels in my view

        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int CarId { get; set; }

        [Required]
        public string Registration { get; set; }

        [Required]
        public virtual CarModels Model { get; set; }

        [Required]
        public string RegistrationYear { get; set; }

        [Required]
        public string ChassisNumber { get; set; }

        [Required]
        public int RegistrationId { get; set; }

And here is the function

public static List<Cars> GetRegistrationCars(int registration)
        {
            List<Cars> registrationCars = new List<Cars>();
            using (var db = new EventsContext())
            {
                registrationCars = db.Cars.Where(c => c.RegistrationId == registration).ToList();
            }

            return registrationCars.ToList();
        }
1
5
2/9/2014 8:43:55 AM

Accepted Answer

Ah ha figured it out in the end Thanks for the suggestions

 public static List<Cars> GetRegistrationCars(int registration)
        {
            List<Cars> registrationCars = new List<Cars>();

            using (var db = new FerrariEventsContext())
            {
                registrationCars = db.Cars.Include(m=> m.Model).Where(c => c.RegistrationId == registration).ToList();
            }

            return registrationCars;
        }
5
2/7/2014 6:14:24 PM

Popular Answer

It's attempting to lazy load the Model property after the list is returned (and the DbContext is disposed). Either eager load the Model property or disable lazy loading/proxy generation.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow