WingMan20-10 WingMan20-10 - 1 month ago 7
C# Question

SelectMany linq multiple collections from the base same entity

I have an object that has many

collections


public class Person
{
public int id {get; set;}
public ICollection<Address> Address {get; set;}
public ICollection<Job> Job {get; set;}
}

public class Adress
{
public bool IsCurrent {get; set;}
}
public class Job
{
public bool IsCurrent {get; set;}
}


A person can have a
list of addresses
but only one is current, and a
list of Jobs
but only one is current.

I need to write a
linq to sql
Entity Framework query where I select the person where
Id= 1
and get the
current job and current address
.

Then select then select some fields from
person, current address and current job
.

Answer

Assuming Job and Address have a boolean field called IsCurrent.

using (YourDbContext context = new YourDbContext()) {
    int id = 1;
    var results = (from person in context.People
                   where person.Id == id
                   select new {
                       Person = person,
                       CurrentJob = person.Job.Where(j => j.IsCurrent).FirstOrDefault(),
                       CurrentAddress = person.Address.Where(a => a.IsCurrent).FirstOrDefault()
                   });
}            

You can change the anonymous object to anything that suits you.