How to retrieve ids of related record using Ardalis Specification

41 Views Asked by At

Is it possible to retrieve list of IDs of related records using Ardalis Specification?

For example, Project table has ProjectId, ProjectName, BuildingId columns. Building table has BuildingId and BuildingName columns. I'd like to retrieve the Project record by ProjectId and include related Building Ids. Project to Building is 1 to many.

public sealed class ProjectByProjectIdSpecification : Specification<ProjectEntity>
{
    public ProjectByProjectIdSpecification(long id)
    {
        Query
            .AsNoTracking()
            .Include(x => x.Buildings) //here I dont want the entire building objects - just the ids
            .Where(x => x.Id == id);
    }
}
1

There are 1 best solutions below

1
On

You can use Select() for your advantage.

public sealed class ProjectByProjectIdSpecification : Specification<ProjectEntity>
{
    public ProjectByProjectIdSpecification(long id)
    {
        Query
            .AsNoTracking()
            .Where(x => x.Id == id)
            .Include(x => x.Buildings)
            .Select(p => new ProjectEntity
            {
                Id = p.Id,
                ProjectName = p.ProjectName,
                BuildingIds = p.Buildings.Select(b => b.BuildingId).ToList()
            });
    }
}

Make sure your ProjectEntity class has following properties.

public class ProjectEntity
{
    public long Id { get; set; }
    public string ProjectName { get; set; }   
    public List<long> BuildingIds { get; set; } // Property to hold BuildingIds
    public List<BuildingEntity> Buildings { get; set; } // Navigation property to related buildings
}

This way you can retrieve the data you want and it should retrieve only the necessary information, including the BuildingIds.