开发者

How to check if a child-object is populated

How can i check if a child-object of a linq-object is populated or not? Example code below.

My model have two methods, one joins data, and the other does not:

public static Member GetMemberWithPhoto(Guid memberId)
{
    using (DataContext db = new DataContext())
    {
        DataLoadOptions dataLoadOptions = new DataLoadOptions();
        dataLoadOptions.LoadWith<Member>(x => x.UserPhoto);
        db.LoadOptions = dataLoadOptions;

        var query = from x in db.Members
                    where x.MemberId == memberId
                    select x;

        return query.FirstOrDefault();
    }
}

public static Member GetMember(Guid memberId)
{
    using (DataContext db = new DataContext())
    {
        var query = from x in db.Members
                    w开发者_开发百科here x.MemberId == memberId
                    select x;

        return query.FirstOrDefault();
    }
}

Then my control have the following code:

Member member1 = Member.GetMemberWithPhoto(memberId);
Member member2 = Member.GetMember(memberId);

Debug.WriteLine(member1.UserPhoto.ToString());
Debug.WriteLine(member2.UserPhoto.ToString());

The last line will generate a "Cannot access a disposed object" exception. I know that i can get rid of that exception just by not disposing the datacontext, but then the last line will generate a new query to the database, and i don't want that.

What i would like is something like:

Debug.WriteLine((member1.UserPhoto.IsPopulated()) ? member1.UserPhoto.ToString() : "none");
Debug.WriteLine((member2.UserPhoto.IsPopulated()) ? member2.UserPhoto.ToString() : "none");

Is it possible?


Is the Settings property defined as an EntitySet? If so, then you should be able to inspect the HasLoadedOrAssignedValues property:

Debug.WriteLine(member1.Settings.HasLoadedOrAssignedValues ? member2.Settings.Count : -1);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜