EF1 SelectMany() left join

本文关键字:left join SelectMany EF1 | 更新日期: 2023-09-27 18:13:37

是否可以使用SelectMany()并使其表现得像左连接?

我正在尝试将实体对象扁平化为表格格式,以便我可以将其用作.rdlc报告的数据源。只要有子对象,SelectMany()就像一个魅力,但是我想看到所有的父对象,不管它是否有子对象。

public class Owner
{
    public int ownerID { get; set; }
    public string ownerName { get; set; }
    public List<Pet> pets { get; set; }
}
public class Pet
{
    public int petID { get; set; }
    public string petName { get; set; }
    public string petType { get; set; }
}
    public void GetOwners()
    {
        List<Owner> owners = new List<Owner>();
        owners.Add(new Owner{ownerID=1, ownerName="Bobby", pets = null});
        owners.Add(new Owner
        {
            ownerID = 2,
            ownerName = "Ricky",
            pets = new List<Pet>(){
                new Pet{petID=1, petName="Smudge", petType="Cat"},
                new Pet{petID=2, petName="Spot", petType="Dog"}}
        });
        var ownersAndPets = owners.SelectMany(o => o.pets
            .Select(p => new { o.ownerName, p.petName }));
    }

这会使ownersAndPets看起来像:
ownerName = "Ricky", petName = "Smudge"
ownerName = "Ricky", petName = "Spot"

我需要的是:
ownerName = "Bobby", petName = null
ownerName = "Ricky", petName = "Smudge"
ownerName = "Ricky", petName = "Spot"

EF1 SelectMany() left join

确保数据集是可枚举的,然后使用"DefaultIfEmpty"

        var ownersAndPets = owners
        .SelectMany(o => o.pets
            .DefaultIfEmpty()
            .Select(p => new 
            { 
                o.ownerName, 
                p.petName 
            }));

注意:我没有测试这段代码,但我以前用过,所以我知道它可以做到。