How to check if an entityset 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
11:44 UTC
Read the original article
Hit count: 208
How can i check if an entityset 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 GetMemberWithSettings(Guid memberId)
{
using (DataContext db = new DataContext())
{
DataLoadOptions dataLoadOptions = new DataLoadOptions();
dataLoadOptions.LoadWith<Member>(x => x.Settings);
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.GetMemberWithSettings(memberId);
Member member2 = Member.GetMember(memberId);
Debug.WriteLine(member1.Settings.Count);
Debug.WriteLine(member2.Settings.Count);
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.Settings.IsPopulated()) ? member1.Settings.Count : -1);
Debug.WriteLine((member2.Settings.IsPopulated()) ? member2.Settings.Count : -1);
Is it possible?
© Stack Overflow or respective owner