-1

given this table

TABLE A(
IdA NUMERIC PRIMARY KEY
,DescA VARCHAR2(200)
)

TABLE B(
IdB NUMERIC PRIMARY KEY
,IdA NUMERIC
,DescB VARCHAR2(200)
)

i want to select

IdA
, DescA
, Count Of B For Each A

into custom DTO

projection with is dto is not a problem but i'am looking a way to add the count to my query

A AAlias = null;
            DtoType myDTO = null;

            return _session.QueryOver<A>(() => AAlias )
          .Select(Projections.Property(() => AAlias.IdA).WithAlias(() => myDTO.IdA),
                  Projections.Property(() => corsoAlias.DescA).WithAlias(() => myDTO.DescA))
            .TransformUsing(Transformers.AliasToBean<DtoType>())
            .List<DtoType>()
            .AsEnumerable();

EDIT: domain object:

public class TableA
{
    public Guid Id { get; set; }
    public string Desc { get; set; }
    public ICollection<B> Bs { get; set; }
}

public class TableB
{
    public Guid Id { get; set; }
    public string Desc { get; set; }
}
gt.guybrush
  • 1,320
  • 3
  • 19
  • 48

1 Answers1

1

As you say, you want to count all TableB for every TableA. You will need a subquery for this.

public class TableA
{
    public Guid Id { get; set; }

    public string Desc { get; set; }
}

public class TableB
{
    public Guid Id { get; set; }

    public TableA TableA { get; set; }

    public string Desc { get; set; }
}

public class Dto
{
    public Guid IdA { get; set; }

    public string DescA { get; set; }

    public int CountOfBForEachA { get; set; }
}


public class MyDtoService : IMyDtoService
{
    private readonly ISession _session;

    public MyDtoService(ISession session)
    {
        _session = session;
    }

    public void GetDto()
    {
        TableA tableA = null;
        TableB tableB = null;
        Dto dto = null;

        var countOfBForEachASubQuery = QueryOver.Of(() => tableB)
            .Where(() => tableB.TableA.Id == tableA.Id)
            .Select(x => tableB.Id);

        var result = _session.QueryOver(() => tableA)
            .Select(Projections.Property(() => tableA.Id),
                Projections.Property(() => tableA.Desc).WithAlias(() => dto.DescA),
                Projections.SubQuery(countOfBForEachASubQuery.DetachedCriteria).WithAlias(() => dto.CountOfBForEachA))
            .TransformUsing(Transformers.AliasToBean<Dto>())
            .List<Dto>();
    }
}
hightech
  • 1,530
  • 1
  • 10
  • 8
  • sorri, i'm so used to it that i forgot to write that model does not have navigation property: i only have list of B in A class. i updated my question – gt.guybrush Aug 26 '21 at 13:27