如何检查是否填充了linq-object的子对象?下面的示例代码。
我的模型有两种方法,一种是连接数据,另一种不是:
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();
}
}
然后我的控件有以下代码:
Member member1 = Member.GetMemberWithPhoto(memberId);
Member member2 = Member.GetMember(memberId);
Debug.WriteLine(member1.UserPhoto.ToString());
Debug.WriteLine(member2.UserPhoto.ToString());
最后一行将生成“无法访问已处置对象”异常。我知道我可以通过不处理datacontext来摆脱异常,但最后一行将生成一个新的数据库查询,我不希望这样。
我想要的是:
Debug.WriteLine((member1.UserPhoto.IsPopulated()) ? member1.UserPhoto.ToString() : "none");
Debug.WriteLine((member2.UserPhoto.IsPopulated()) ? member2.UserPhoto.ToString() : "none");
有可能吗?
答案 0 :(得分:1)
Settings属性是否定义为EntitySet?如果是这样,那么您应该能够检查HasLoadedOrAssignedValues属性:
Debug.WriteLine(member1.Settings.HasLoadedOrAssignedValues ? member2.Settings.Count : -1);