0

I have Salary table where I have those fields :

 public int Id { get; set; }
public DateTime Date { get; set; }
public decimal Amount { get; set; }
public Nullable<int> Employee_Id { get; set; }

public virtual Employee Employee { get; set; }

Here is SalariesViewModel

public class SalariesViewModel
    {
        public string DepartmentName { get; set; }
        public decimal AverageSalary { get; set; }

        public double MaxDifference { get; set; }
    }

I need to get average salary and also I need to calculate max difference between payment dates. For example employee has 3 salary pays. I need to show max time between those pays. So it would be 3 payment -2 payment , and 2 payment - 1 payment. and if for example 1 variant difference is bigger, I need to show it.

I wrote this repo method

 public List<SalariesViewModel> GetAverageSalary() {

        var maxdiff = 0;
        List<SalariesViewModel> result = new List<SalariesViewModel>();
        var employees = db.Employees.Select(x => new
        {
            Department = x.Department.Name,
            Name = x.Name,
            Salary = x.Salaries.OrderByDescending(y => y.Date).FirstOrDefault().Amount,
            Date = x.Salaries.OrderByDescending(y => y.Date).FirstOrDefault().Date 

        });



        var data = employees.GroupBy(m => m.Department).Select(x => new SalariesViewModel
        {
            DepartmentName = x.Key,
            AverageSalary = x.Average(y => y.Salary),
            MaxDifference = x.Select(y => y.Date).ToList().Zip(x.Select(y => y.Date).Skip(1), (c, n) => (n - c).TotalSeconds).Max()

        }).ToList();





        return data;
    }

But I have this error

LINQ to Entities does not recognize the method 'System.Collections.Generic.IEnumerable1[System.Double] Zip[DateTime,DateTime,Double](System.Collections.Generic.IEnumerable1[System.DateTime], System.Collections.Generic.IEnumerable1[System.DateTime], System.Func3[System.DateTime,System.DateTime,System.Double])' method, and this method cannot be translated into a store expression.

In this row MaxDifference = x.Select(y => y.Date).ToList().Zip(x.Select(y => y.Date).Skip(1), (c, n) => (n - c).TotalSeconds).Max()

How I can solve it?

NetMage
  • 26,163
  • 3
  • 34
  • 55
Balance
  • 167
  • 2
  • 11
  • This might relate https://stackoverflow.com/questions/7259567/linq-to-entities-does-not-recognize-the-method – mike123 Feb 13 '18 at 15:51
  • 3
    You can't use .Zip() because Linq to entities can't translate it to SQL. You could materialize your query and call Zip() in memory. – Fran Feb 13 '18 at 15:51
  • It seems like you are computing the `MaxDifference` between different employees in the same department and not between salary pays for a single employee? – NetMage Feb 13 '18 at 21:30

0 Answers0