繁体   English   中英

System.ObjectDisposedException 与实体框架中的 Virtual 属性

[英]System.ObjectDisposedException with Virtual property in 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();
        }

啊哈终于想通了 谢谢你的建议

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

它试图在返回列表后延迟加载Model属性(并且DbContext已处理)。 预先加载Model属性或禁用延迟加载/代理生成。

在调用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调用实际上并不存在(我第一次没有发现),但现在我希望这是一个错字:)

还有一个建议: GetRegistrationCars()应该是异步的——通过将ToList()更改为ToListAsync()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM