Quantcast
Channel: ADO.NET, Entity Framework, LINQ to SQL, NHibernate
Viewing all articles
Browse latest Browse all 1698

LINQ Get joined objects or null if not

$
0
0

I have two tables :

class Cat {
    [Key]
    public Guid Id { get; set; }
    public string Name { get; set; }
}

class Dog {
    [Key]
    public Guid Id { get; set; }
    public virtual Cat Kitty { get; set; }
    public string Name { get; set; }
}

and a view model

class ResultViewModel
{
    public Guid Id { get; set; }
    public Guid DogId { get; set; }
    public string Name { get; set; }
    public string DogName { get; set; }
}

What I'd like to do looks something like :

async Task<List<ResultViewModel>> GetCatsAndDogs()
{
    return await (
        from cat in dbContext.Cats
        from dog in dbContext.Dogs
        where cat.Id == dog.Kitty.Id
        select new ResultViewModel {
            Id = cat.Id,
            Name = cat.Name,
            DogId = (dog == null) ? Guid.Empty : dog.id,
            DogName = (dog == null) ? string.Empty : dog.Name
        }
    )
    .ToListAsync()
}

What I can't figure out is how to get instances of Cat where there are no corresponding instances of Dog.

Please help :)


Viewing all articles
Browse latest Browse all 1698

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>