Search code examples
c#sqllambdaedmxdomaindatasource

SUM and GROUPBY lambda expression on DataDomainService


I have a Silverlight application and a gridview bound from a domaindatasource control, and i am querying a view from domain data source using two parameters, but from the result, i need to sum 4 columns, grouping by the others.

My Model View

My metadata class:

internal sealed class vwAplicacoesMetadata
    {
        // Metadata classes are not meant to be instantiated.
        private vwAplicacoesMetadata()
        {
        }

        public Nullable<int> CodInternoCliente { get; set; }

        public Nullable<int> CodTipoOper { get; set; }

        public string CPFCNPJCliente { get { return this.CPFCNPJCliente; } set { String.Format("{0,-14}", value); } }

        public string TipoClientePFPJ { get; set; }

        public string NomeCliente { get; set; }

        public DateTime DataOper { get; set; }

        public decimal LCQtde { get; set; }

        public decimal LCValor { get; set; }

        public decimal LDQtde { get; set; }

        public decimal LDValor { get; set; }
    }
}

And the IQueryable function i need to use the groupby and sum expressions:

public IQueryable<vwAplicacoes> GetVwAplicacoesPorData(DateTime pstrDataInicio, DateTime pstrDataFinal)
    {
        return this.ObjectContext.vwAplicacoes.Where(d => d.DataOper > pstrDataInicio && d.DataOper < pstrDataFinal)
    }

Its working, and now i need to group by CPFCNPJCliente, NomeCliente, TipoClientePFPJ, CodInternoCliente and CodTipoOper, and sum the fields LCValor, LCQtde, LDValor, LDQtde.

Any suggestion?


Solution

  • Try this:

    return this.ObjectContext.vwAplicacoes
           .Where(d => d.DataOper > pstrDataInicio && d.DataOper < pstrDataFinal)
           .GroupBy(x => new {x.CPFCNPJCliente,x.NomeCliente,x.TipoClientePFPJ,x.CodInternoCliente,x.CodTipoOper})
           .Select(k => new {key = k.Key, 
                             totalLCValor = k.Sum(x=>x.LCValor),
                             totalLCQtde = k.Sum(x=>x.LCQtde),
                             totalLDValor = k.Sum(x=>x.LDValor),
                             totalLDQtde = k.Sum(x=>x.LDQtde)})