System.ObjectDisposedException with virtual property in essence

Hi, can anyone help with this. I get the above error when trying to display Karmodel data 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();
        }
+3
source share
3 answers

Aaaaaaaaaaaaaaaaaaaaaaa at the end

 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;
        }
+2
source

It tries to be lazy to load the property Modelafter returning the list (s DbContext). Either load the property Modelor disable lazy loading / creating proxies.

+2
source

, ToList(). ToList() using

    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();
        }
        // Here is too late - using has Disposed() the EventsContext() already so ToList will throw an exception
     }

Edit:

It is assumed that the call ToListin the linq request is actually missing (I did not notice this first round), but now I hope this is a typo :)

0
source

All Articles