❔ Querying Many to Many EF Relationships
What is the best way to query Many to Many relationships? I'm using Ardalis.Specification package and this is my current workaround to get a Job's list of Contacts. It feels like there is something simpler staring at me
Content: I'm using JobContact in either side of this relationship.
Content: I'm using JobContact in either side of this relationship.
public sealed class GetJobContactsSpecification : Specification<Job, List<Contact>>
{
public GetJobContactsSpecification(Guid jobId, string userId)
{
Query
.Select(x => x.Contacts.ToList())
.Include(x => x.Contacts)
.ThenInclude(x => x.Companies)
.Include(x => x.Contacts)
.ThenInclude(x => x.Phones)
.Include(x => x.Contacts)
.ThenInclude(x => x.Emails)
.AsSplitQuery()
.AsNoTracking()
.Where(x => x.Id == jobId && x.OwnerId == userId);
}
}public sealed class GetJobContactsSpecification : Specification<Job, List<Contact>>
{
public GetJobContactsSpecification(Guid jobId, string userId)
{
Query
.Select(x => x.Contacts.ToList())
.Include(x => x.Contacts)
.ThenInclude(x => x.Companies)
.Include(x => x.Contacts)
.ThenInclude(x => x.Phones)
.Include(x => x.Contacts)
.ThenInclude(x => x.Emails)
.AsSplitQuery()
.AsNoTracking()
.Where(x => x.Id == jobId && x.OwnerId == userId);
}
}public class Job : Entity
{
// Database Relationship Properties
public List<JobContact> JobContacts { get; set; }
// Rest of properties....
}public class Job : Entity
{
// Database Relationship Properties
public List<JobContact> JobContacts { get; set; }
// Rest of properties....
}public class Contact : Entity
{
// Database Relationship Properties
public List<JobContact> JobContacts { get; set; }
// Rest of properties....
}public class Contact : Entity
{
// Database Relationship Properties
public List<JobContact> JobContacts { get; set; }
// Rest of properties....
}public class JobContact
{
public Guid JobId { get; set; }
public Job Job { get; set; }
public Guid ContactId { get; set; }
public Contact Contact { get; set; }
}public class JobContact
{
public Guid JobId { get; set; }
public Job Job { get; set; }
public Guid ContactId { get; set; }
public Contact Contact { get; set; }
}