How to check if a child-object is populated

Posted by TheQ on Stack Overflow See other posts from Stack Overflow or by TheQ
Published on 2010-06-03T11:42:10Z Indexed on 2010/06/03 12:34 UTC
Read the original article Hit count: 186

Filed under:
|
|

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
                    where 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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about asp.net-mvc