Linq从多个联接中选择并返回所有行,即使表未返回匹配项

时间:2018-11-29 14:12:11

标签: linq linq-to-sql

将此结构与4个表一起考虑。 childinfo,motherinfo,fatherinfo和Guardianinfo。 childinfo表还具有motherid,fatherid和Guardianid

即使母亲信息,父亲信息或监护人信息表中没有任何内容,我仍试图基于ID获取孩子的所有数据。

我的查询是这样的:

 var joined = (from c in _context.ChildInfo.Where(c => c.ChildDob >= dobDtRange.DobStart && c.ChildDob <= dobDtRange.DobEnd)
                          .OrderByDescending(c => c.ChildId)
                          join m in _context.MotherInfo.DefaultIfEmpty() on c.MotherId equals m.MotherId into cm
                          from cmm in cm.DefaultIfEmpty()
                          join f in _context.FatherInfo.DefaultIfEmpty() on c.FatherId equals f.FatherId into cf
                          from cff in cf.DefaultIfEmpty()
                          join g in _context.Guardian.DefaultIfEmpty() on c.GuardianId equals g.GuardianId into cg
                          from cgg in cg.DefaultIfEmpty()
                          select new { c, cmm, cff, cgg })

这不起作用,我在做什么错了?

1 个答案:

答案 0 :(得分:1)

似乎您有一个One-to-Zero-or-One Relationship,如果您的孩子没有母亲,则其外键MotherId为零。某些系统的外键值为空而不是零。

要获取带有其母亲的孩子,或者如果该孩子的外键值为零,则为null母亲,对于父亲,则为类似值,等等:

var result = dbContext.Children.Select(child => new
{
    // select only the Child properties you actually plan to use
    Id = child.Id,
    Name = chid.Name,
    ...

    Mother = dbContext.Mothers
        .Where(mother => mother.Id == child.MotherId)
        .Select(mother => new
        {   // select only the mother properties you actually plan to use
            Id = mother.Id,
            Name = mother.Name,
            ...
        })
        .FirstOrDefault(), // will return null if there is no mother for this foreign key
    Father = dbContext.Fathers
        .Where(father => father.Id == child.FatherId)
        .Select(father => new
        {   // select only the father properties you actually plan to use
            Id = father.Id,
            Name = father.Name,
            ...
        })
        .FirstOrDefault(), // will return null if there is no father for this foreign key
         ... etc