简体   繁体   English

编码第一个一对多关系

[英]Code first one to Many relationship

I have defined one to many relationship like this 我已经定义了这样的一对多关系

    public class ClassA
    {
        [Key, ForeignKey("ClassB"), Column(Order = 0)]
        public int ClassB_ID { get; set; }
         [Key, Column(Order=1)]
        public string  name { get; set; }
        public bool IsApproved { get; set; }
        public virtual ClassB ClassB { get; set; }
     }
    public class ClassB
    {
     [Key]
     public int ID{get;set;}
     public string Name{get;set;}
     public virtual ICollection<ClassA> classAs{get;set;}
    }

Works fine until I bind classA to a Listview with Bind(ClassB.Name) 正常工作,直到我将classA绑定到具有Bind(ClassB.Name)的Listview

I get The ObjectContext instance has been disposed and can no longer be used for operations that require a connection. 我得到了ObjectContext实例已被处置,不能再用于需要连接的操作。

This could be because of using Lazy Loading . 这可能是因为使用了惰性加载 Which cause the additional round trip to database when trying to access with navigation property (ClassA), but your context is already disposed. 尝试使用导航属性(ClassA)进行访问时,这会导致数据库的额外往返行程,但是您的上下文已被释放。

Lazy Loading : When the entity is first read, related data isn't retrieved. 延迟加载 :首次读取实体时,不会检索相关数据。 However, the first time you attempt to access a navigation property, the data required for that navigation property is automatically retrieved. 但是,第一次尝试访问导航属性时,将自动检索该导航属性所需的数据。 This results in multiple queries sent to the database. 这导致将多个查询发送到数据库。

You could probably solve this problem with Eager Loading Include() or Explicit loading . 您可能可以通过急切加载 Include()显式加载解决此问题。

var values = context.ClassB.Include("ClassA").ToList()

http://www.asp.net/web-forms/tutorials/continuing-with-ef/maximizing-performance-with-the-entity-framework-in-an-asp-net-web-application http://www.asp.net/web-forms/tutorials/continuing-with-ef/maximizing-performance-with-the-entity-framework-in-an-asp-net-web-application

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

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