Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.ObjectDisposedException with Virtual property in entity framework

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();
        }
like image 934
rs82uk Avatar asked Feb 07 '14 17:02

rs82uk


2 Answers

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;
        }
like image 126
rs82uk Avatar answered Nov 15 '22 07:11

rs82uk


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.

like image 41
Moho Avatar answered Nov 15 '22 06:11

Moho