问题
I've a Linq to sql query:
IEnumerable<PY_History_TransactionTAB> FilteredReport;
var ReportData = db.PY_History_TransactionTAB.AsEnumerable()
.Where(x => x.SystemCode == SysCode)
.GroupBy(x => new
{
x.EmployeeCode,
x.EmployeeMaster.Emp_FullName,
x.Designations.Title,
department = x.Departments.Title
});
FilteredReport = ReportData.Select(x => new PY_History_TransactionTAB
{
EmployeeCode = x.Key.EmployeeCode,
H_SalaryDays = x.Sum(y => y.H_SalaryDays ?? 0),
H_NET_Overtime = x.Sum(y => y.H_NET_Overtime),
H_Overtime_Amount = x.Sum(y => y.H_Overtime_Amount),
H_SL_Breakup1 = x.Sum(y => y.H_SL_Breakup1 ?? 0),
H_OT_Allowance1 = x.Sum(y => y.H_OT_Allowance1 ?? 0),
}).ToList();
Now, if I want to add the GroupBy member x.EmployeeCode
in Select(), it takes it, and works fine, but I don't know how to include a navigation property x.EmployeeMaster.Emp_FullName
to Select(), which is a next member of GroupBy(). I know that the model PY_History_TransactionTAB
to which I am refering in Select() does not contain definition for Emp_FullName
but it contains definition for a navigation property i.e. EmployeeMaster
.
So, Is there a way to include a navigation property x.EmployeeMaster.Emp_FullName
to the Select() so that I can access them in a strongly typed view?
Below is my View just for convenience :
@model IEnumerable<HrAndPayrollSystem.Models.PY_History_TransactionTAB>
<tr>
<th>
@Html.DisplayNameFor(model => model.EmployeeCode)
</th>
<th>
@Html.DisplayNameFor(model => model.Departments.Title)
</th>
<th>
@Html.DisplayNameFor(model => model.EmployeeMaster.Emp_FullName)
</th>
<th>
@Html.DisplayNameFor(model => model.Designations.Title)
</th>
<th>
@Html.DisplayNameFor(model => model.H_SalaryDays)
</th>
.
.
. // Other Elements
</tr>
In the above View, I can access model.EmployeeCode
but what I cannot access is model.EmployeeMaster.Emp_FullName
and similarly other navigation properties.
So, my question is that how do I modify my linq to sql query to get the result view right?
回答1:
Modify your query this way :
FilteredReport = ReportData.Select(x => new PY_History_TransactionTAB
{
EmployeeCode = x.Key.EmployeeCode,
EmployeeMaster = x.First().EmployeeMaster,
.
. // other attributes
.
}).ToList();
来源:https://stackoverflow.com/questions/39748691/how-to-include-the-groupby-elements-in-select-in-linq-to-sql-query