代码之家  ›  专栏  ›  技术社区  ›  asfsadf

海关:一定是我做错了什么

  •  2
  • asfsadf  · 技术社区  · 15 年前

    我一直在添加我的不同实体的部分类来添加各种有用的方法。

    根据我看到的例子,尝试添加属性似乎很简单,但我的却失败得很惨。

    更新

            public List<Friend> FriendsInGoodStanding
        {
            get
            {
                using (var context = new GarbageEntities())
                {
                    var a = context.Friends.Include("aspnet_User1").Where(f => f.UserID == this.UserId && f.Blocked == false).ToList();
                    var b = context.Friends.Include("aspnet_User").Where(f => f.FriendUserID == this.UserId && f.Blocked == false).ToList();
                    a.AddRange(b);
                    return a.Distinct().ToList();
                }
            }
        }
    

    每当我尝试使用此属性时,都会收到以下错误:

    ObjectContext实例已被删除 已处理,不能再用于 需要连接的操作。

    Line 4936:            get
    Line 4937:            {
    Line 4938:                return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<aspnet_User>("GarbageModel.FK_Friends_aspnet_Users", "aspnet_User").Value;
    Line 4939:            }
    

    这肯定是我忽略了的事情。

    1 回复  |  直到 15 年前
        1
  •  4
  •   Morteza Manavi    15 年前

    这个错误的来源是因为你的程序试图“延迟加载”你的朋友实体对象上的一个导航属性,当你已经读了这个属性时就会发生这种情况 友谊之旅
    现在,我可以看到您正在急切地加载“aspnet\u User1”,并且在查询的末尾调用ToList(),因此它一定是 朋友 对象。如果显示使用 友谊之旅

    public partial class aspnet_User{
    
        public List FriendsInGoodStanding {
            get {
                using (var context = new GarbageEntities()) {
    
                    var a = context.Friends
                         .Include("aspnet_User1")
                         .Include("aspnet_User")
                         .Where(f => f.UserID == this.UserId && f.Blocked == false).ToList();
    
                    var b = context.Friends
                         .Include("aspnet_User")
                         .Include("aspnet_User1")
                         .Where(f => f.FriendUserID == this.UserId && f.Blocked == false).ToList();
                    a.AddRange(b);
                    return a.Distinct().ToList();
                }
            }
        }
    }
    



    另一种解决方案:
    会是 以便对象上下文克服此异常。您可以通过右键单击您的模型,然后选择properties,然后找到默认为true的“Lazy Loading Enabled”选项,只需将其设置为false。或者可以编程方式编写:

    var context = new GarbageEntities();
    context.ContextOptions.LazyLoadingEnabled = false;
    

    一旦被禁用,您仍然可以根据需要显式加载相关数据,或者 小心NullReferenceException!