System.ObjectDisposedException,在实体框架中具有Virtual属性

时间:2014-02-07 17:53:59

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

大家可以帮忙解决这个问题我试图在我的视图中显示有关Carmodels的数据时遇到上述错误

        [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; }

这是函数

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();
        }

4 个答案:

答案 0 :(得分:3)

啊哈哈最后想出来了谢谢你的建议

 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;
        }

答案 1 :(得分:2)

在返回列表后,它试图延迟加载Model属性(并释放DbContext)。要么加载Model属性,要么禁用延迟加载/代理生成。

答案 2 :(得分:0)

在您调用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
     }

编辑:

这假设对linq查询的ToList调用实际上并不存在(我没有发现第一次),但现在我希望这是一个错字:)

答案 3 :(得分:-1)

另外一个建议:GetRegistrationCars() 应该是异步的 - 将 ToList() 更改为等待 ToListAsync()