Search By Entity with EF

Asked

Viewed 97 times

-1

I’m new to the business and I’m on my first steps.

I am trying to create a system of financial consolidation. I need it to return me the total expenses of a certain Rubric.

using System;
using System.Linq;
using System.Web;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Siscongest.Models
{
    public class Despesa
    {
        [Key]
        public int IdDespesa { get; set; }

        [Range(1, double.MaxValue, ErrorMessage = "Selecione a Empresa")]
        [Display(Name = "Empresa")]
        public int IdEmpresa { get; set; }

        [Range(1, double.MaxValue, ErrorMessage = "Selecione a Rubrica")]
        [Display(Name = "Rubrica")]
        public int IdRubricaDespesa { get; set; }       

        [Required(ErrorMessage = "O campo {0} é requerido!!")]
        [MaxLength(150, ErrorMessage = "O campo {0 } recebe no máximo {1} caracteres")]
        [Display(Name = "Descrição")]
        public string Descricao { get; set; }

        [DataType(DataType.Date)]
        [Required(ErrorMessage = "O campo {0} é requerido!!")]
        [Display(Name = "Data da Despesa")]
        public DateTime DataDespesa { get; set; }

        [Required(ErrorMessage = "O campo {0} é requerido!!")]
        [Display(Name = "Valor da Despesa")]
        public double Valor { get; set; }

        [Range(1, double.MaxValue, ErrorMessage = "Selecione a Moeda")]
        [Required(ErrorMessage = "O campo {0} é requerido!!")]
        [Display(Name = "Moeda")]
        public int IdMoeda { get; set; }

        public virtual Moeda Moeda { get; set; }
        public virtual RubricaDespesa RubricaDespesa { get; set; }
        public virtual Empresa Empresa { get; set; }
    }
}

I have the complete Expense List :

public ActionResult Index()
        {
            var despesas = db.Despesas
                .Include(d => d.RubricaDespesa)
                .Include(d => d.Empresa)
                .Include(d => d.Moeda);
            return View(despesas.ToList());
        }

I need him now to return me to List with the Total for Rubric , Total per Companies and Total by Coins.

I’m trying to use the code for the report but it doesn’t work

 public ActionResult GraficoDespesaRubrica(int? idRubrica)
            {
                var list = db.Despesas.OrderBy(d => d.DataDespesa)
                   .Where(d => d.IdRubricaDespesa == idRubrica);
                foreach(var rubri in list)
                {
                    list.Where(d => d.IdRubricaDespesa == idRubrica).
                        Sum(d => d.Valor);
                }
               var rubrica = new List<int>();
                var val = list.Select(x => x.Valor);
                var data = list.Select(x => x.RubricaDespesa.Descricao);

                var rub = rubrica;
                ViewBag.VALOR = val;
                ViewBag.Data = data;
         }

3 answers

1

Without your whole data model and possible business rules, I think this is for the total expenses of a given Rubric:

public double DespesaTotalPorRubrica(int idRubrica){
    var total = db.Despesas
        .Where(d => d.IdRubricaDespesa == idRubrica)
        .Sum(d => Valor);
    return total;
}

By determined Enterprise:

public double DespesaTotalPorEmpresa(int idEmpresa){
    var total = db.Despesas
        .Where(d => d.IdEmpresa == idEmpresa)
        .Sum(d => Valor);
    return total;
}

By determined Coin:

public double DespesaTotalPorMoedas(int idMoedas){
    var total = db.Despesas
        .Where(d => d.IdMoeda == idMoedas)
        .Sum(d => Valor);
    return total;
}

Your example and comments:

public ActionResult GraficoDespesaRubrica(int ? idRubrica) 
{
    var list = db.Despesas.OrderBy(d => d.DataDespesa)
        .Where(d => d.IdRubricaDespesa == idRubrica); // Aqui tem todas as Despesas da Rubrica com o id igual a idRubrica
    foreach(var rubri in list) { //este foreach não irá fazer nada nem entendo o seu motivo, está a iterar cada Despesa em list, mas depois nem usa rubri e dentro do foreach está de novo a filtrar por id, não faz nenhum sentido.
        list.Where(d => d.IdRubricaDespesa == idRubrica).
        Sum(d => d.Valor);
    }

    var rubrica = new List < int > (); // Está a criar uma nova lista e depois não a usa para nada.
    var val = list.Select(x => x.Valor);
    var data = list.Select(x => x.RubricaDespesa.Descricao);

    var rub = rubrica; // Para que é esta variável?
    ViewBag.VALOR = val;
    ViewBag.Data = data;
}

If you are entering the Heading id then only one figure will appear which is the sum of all the expenses corresponding to that Rubric.

For a graph you need several values. It also doesn’t make sense to have a date if it’s multiple expenses so it has multiple dates.

Your example written correctly:

public ActionResult GraficoDespesaRubrica(int? idRubrica)
{
    var total = DespesaTotalPorRubrica(idRubrica);

    ViewBag.VALOR = total;
}

Expenditure figures by Heading:

db.Despesas
  .Include(d => d.RubricaDespesa) //incluir as Rubricas
  .Include(d => d.Moeda)          //incluir as Moedas
  .GroupBy(                       
    d => d.IdRubricaDespesa,      //agrupar as despesas por id da Rubrica
    (id, ld) => new {             //id's das Rubricas e lista de Despesas por id
      DescricaoRubrica = ld.First().RubricaDespesa.Descricao, //Descricao da primeira Rubrica, todas as Rubricas devem ter a mesma descricao porque são a mesma Rubrica
      ValorTotal = ld.Sum(d => d.Valor) //Soma de todos os valores das Despesas
      Moedas = ld.Select(d => d.Moeda) //Lista de Moedas das Despesas da Rubrica, cada Despesa pode ter uma Moeda diferente e por isso cada Rubrica também
    })

Values of Expenses by Company:

db.Despesas
  .Include(d => d.Empresa)        //incluir as Empresas
  .Include(d => d.Moeda)          //incluir as Moedas
  .GroupBy(                       
    d => d.IdEmpresa,             //agrupar as despesas por id da Empresa
    (id, ld) => new {             //id's das empresas e lista de Despesas por id
      NomeEmpresa = ld.First().Empresa.Nome, //Descricao da primeira Empresa, todas as Empresas devem ter o mesmo nome porque são a mesma Empresa
      ValorTotal = ld.Sum(d => d.Valor) //Soma de todos os valores das Despesas
      Moedas = ld.Select(d => d.Moeda) //Lista de Moedas das Despesas da Empresa, cada Despesa pode ter uma Moeda diferente e por isso cada Empresa também
    })
  • I tried and it didn’t work

  • What didn’t work? You asked for a lot of things and I asked you to indicate the format of the final list.

  • Would you like a normal listing, or return in graphic form

  • What is the format of the list? what objects do you have? If you want totals by each entity want id’s indication together with totals?

  • I want a list of Totals by Items, Totals by Company and by Currencies

  • Mauroalmeida?

  • Someone who can help me?

  • "I want a list of Totals by Items, Totals by Company and by Currencies" - This does not explain how you want objectively the data, you have to give a concrete example of the format of the final result.

  • Something Like What

  • wanted a listing with the sum of all Items, Description of Item - Total Value - Currency

  • I wonder if you could help me remotely?

  • Can someone give me a little help?

  • Manuel, see if this is what you want, I don’t know your Model for Headings and for Companies, but from what you asked I calculated that the Rubric had a field Description and the Enterprise a field Name. If my answers have helped you to learn and to solve your problem, or part of it, put the answer as accepted.

  • Now I’m Getting This Error " The model item passed into the Dictionary is of type 'System.Data.Entity.Infrastructure.Dbquery1[<>f__AnonymousType42[System.String,System.Double]]', but this Dictionary requires a model item of type 'System.Collections.Generic.Ienumerable`1[Siscongest.Models.Expense]'. "

  • on which code line?

  • when I call - http://localhost:54990/Expenses/Jobsworking. I wonder if you could help me remotely?

  • I tried several ways and I couldn’t. I don’t know how you could help me

Show 12 more comments

-1

Your example written correctly:

public ActionResult GraficoDespesaRubrica(int? idRubrica)
{
    var total = DespesaTotalPorRubrica(idRubrica);

    ViewBag.VALOR = total;
}

with regard to that code of yours! I need the chart to show me the total of the monthly expenses, I wanted it to be one for the Rubrics and one for the Companies. and I really wanted to see all the headings so maybe I shouldn’t use the int? idRubrica, if you can help me, as I said I’m a junior and I’m starting to take my first steps

-1

  • You are not matching the View with the data returned from the server, you are not getting Binding right. Please do not put answers to add anything to your question, edit the question. Your initial question has already been answered according to the request, you should mark it as correct. These are other issues and that’s not how Stackoverflow works.

  • You did not specify the type of object the View is prepared to receive and know how to map to HTML. I cannot infer that from the Server nor from your answers, you must be specific in what you ask.

  • Your View is waiting for Ienumerable<Expenses> as indicated in the error. But What you asked for was not that object. You asked for a grouping of Totals by Company and by Rubrics and this was returned. You must modify your View according to the object returned from the Server.

  • and how I resolve this view issue

  • Switch View to the one you want. Accept the answer I gave and create another question with the View part to help with that too.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.