我有3张表,雇员,部门和薪水
这是部门模型:
public partial class Department
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Department()
{
this.Employees = new HashSet<Employee>();
}
public int Id { get; set; }
public string Name { get; set; }
public Nullable<int> Parent_Id { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Employee> Employees { get; set; }
}
这是员工模型:
public partial class Employee
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Employee()
{
this.Salaries = new HashSet<Salary>();
}
public int Id { get; set; }
public string Name { get; set; }
public Nullable<int> Department_id { get; set; }
public virtual Department Department { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Salary> Salaries { get; set; }
}
这是薪资模式:
public partial class Salary
{
public int Id { get; set; }
public Nullable<System.DateTime> Date { get; set; }
public Nullable<decimal> Amount { get; set; }
public Nullable<int> Employee_Id { get; set; }
public virtual Employee Employee { get; set; }
}
我需要获得每个部门的平均工资
所以我为它创建了ViewModel
public class SalariesViewModel
{
public string DepartmentName { get; set; }
public decimal AverageSalary { get; set; }
}
尝试编写此方法
**public List<SalariesViewModel> GetAverageSalary() {
var massagedEmployees = db.Employees.GroupBy(e => e.Department)
.Select(g =>
new {
Department = g.Key,
SalaryAvg = g.Average(x => x.Salaries)
});
}**
但我无法设置x.Salaries.Amount
。
我如何计算每个部门的平均工资?
更新
以下是Department,Employees和Salary的示例输入
薪资投入
雇员输入
部门输入
所以在输出时我需要像这样的部门 - 200 $
答案 0 :(得分:2)
由于您需要员工当前工资的平均值,请将其分为2个查询
首先生成一个包含员工当前工资的对象
var employees = db.Employees.Select(x => new
{
Department = x.Department.Name,
Name = x.Name,
Salary = x.Salaries.OrderByDescending(y => y.Date).First().Amount
});
请注意,这假定员工至少包含一个薪水
接下来按Department
var data = employees.GroupBy(m => m.Department).Select(x => new SalariesViewModel
{
DepartmentName = x.Key,
AverageSalary = x.Average(y => y.Salary)
}).ToList();
return data;
答案 1 :(得分:0)
正如许多人在评论中所解释的那样,您可能正在寻找基于最近一个月的平均工资。在这种情况下,你可以通过
得到这个Employees.GroupBy(e => e.Department.Name)
.Select(g =>
new {
Department = g.Key,
SalaryAvg = g.Average(x => x.Salaries.OrderByDescending(s => s.Date).FirstOrDefault().Amount)
});
如果你坚持要获得针对员工的所有可用价值(我怀疑),你可以这样做
Employees.GroupBy(e => e.Department.Name)
.Select(g =>
new {
Department = g.Key,
SalaryAvg = g.Average(x => x.Salaries.Average(s => s.Amount))
});
注意:上述查询中没有处理空值。