高级LINQ查询帮助

时间:2011-02-13 16:30:05

标签: c# linq-to-sql

所以我有以下LINQ查询:

var qryVans = from v in objContext.vans

                join s in objContext.schools on v.schoolID equals s.schoolID
                join l in objContext.locations on v.lastKnownLocationID equals l.locationID

                select new DisplayVan {
                    vanID = v.vanID,
                    vanName = v.vanName,
                    phone = v.phone,
                    capacity = (int)v.capacity,
                    schoolName = s.schoolName,
                    lastLocationName = l.locationName,
                    statusNote = v.statusNote,
                    isOffline = (v.isOffline == 1) ? true : false,
                    isPrayerRoom = (v.isPrayerRoom == 1) ? true : false,
                    isNotReady = (v.isNotReady == 1) ? true : false,
                    creationDate = v.creationDate,
                    modifiedDate = v.modifiedDate,
                    vanAssignments = from a in v.vanAssignments
                                    where a.vanID == v.vanID
                                    select a
                };

一切正常,但我需要填充VanAssignment实体的导航属性。请注意,在我的DisplayVan投影中,我使用嵌套查询来收集给定货车的货车分配。 vanAssignment实体具有个人实体。那么如何在此查询中加载vanAssignment.person属性?

另外,我可以写这个更有效吗?

感谢您的帮助!

修改

以上是我上面的代码失败的地方:

在上面的查询中执行toList()之后,我将尝试访问所需的人:

List<DisplayVan> lstVans = qryVans.toList<DisplayVan>();
foreach(DisplayVan objVan in lstVans) {

   Console.WriteLine(objVan.person.firstName);

}

现在,由于我没有使用vanAssignment实体加载person实体,因此person navigation属性为null,并且会抛出错误。

我的问题围绕在此人物实体中加载vanAssignment的正确方法?

希望有所帮助。

3 个答案:

答案 0 :(得分:1)

我不是Linq to sql expert,但发现了这个:

DataLoadOptions dataLoadOptions = new DataLoadOptions();
dataLoadOptions.LoadWith<Assignment>(a => a.Person);
objContext.LoadOptions = dataLoadOptions;

设置DataLoadOptions会使Person热切加载Assignment。

修改

这肯定在EF中工作,但也应该在Linq to SQL中工作:

(from a in v.vanAssignments
where a.vanID == v.vanID
select new { Assignment = a, Person = a.Person }).Select(i => i.Assignment);

答案 1 :(得分:1)

由于DisplayVan听起来像DTO,为什么不选择显式引用所需人物属性的DisplayVanAssignment对象。

答案 2 :(得分:0)

您可以为此人分配

...
 modifiedDate = v.modifiedDate,
 vanAssignments = GetVanAssignmentsWithPerson(v.vanAssignments.where(a => a.VanID == v.vanID), person)
...

private static IEnumerable<Assignment> GetVanAssignmentsWithPerson(IEnumerable<Assignment> assignments, Person p)
{
      foreach(var assignment in assignments)
      {
           assignment.person = p;
      }
}