Imoum
Imoum

Reputation: 745

Calculate sum using Entity Framework

I'm building a WPF application and my model is like this :

public class Employee
{
        public int Matricule { get; set; }
        public string Nom { get; set; }
        public string Prenom { get; set; }
        public double Salaire { get; set; }

        public Employee() { }
}

public class Ouvrier : Employee
{
        public Ouvrier() { }
}

public class Manager : Employee
{
        public List<Ouvrier> Ouvriers { get; set; }

        public Manager()
        {
        }
}

So the salary of the manager is [his salary+bonus (2% of the sum of his workers salary)]. How can I calculate his salary using Entity Framework? And should I do the calculation in the Manager constructor or in ViewModel?

Upvotes: 0

Views: 582

Answers (2)

Shyju
Shyju

Reputation: 218722

You can can call Sum method on the Outviers Salary property and add that to the manager salaray.

var mgrWithBonus =  dbContext.Managers.Select(s => new Manager 
                           {    
                              Nom = s.Nom,
                              Salaire = s.Salaire +
               (s.Ouvriers!=null? s.Ouvriers.Select(f => f.Salaire).Sum()*0.02:0)
                           }).ToList();

Upvotes: 1

Maxim Fleitling
Maxim Fleitling

Reputation: 562

Here Linq statement to get final salary for all managers.I susppose that managers is DbSet provided by DbContext:

     var managersWithFilnalSalary = managers.Select(m => 
new {m.Nom, FinalSalary = m.Salaire + (m.Ouvriers.Sum(o => o.Salaire)*0.02)});

Upvotes: 0

Related Questions