i want to to display all items from my parent table with selected items from child table and create a list of them to pass to my view.
public ActionResult Index()
{
int Month = DateTime.Now.Month;
List<EmployeeAtt> empWithDate = new List<EmployeeAtt>();
var employeelist = _context.TblEmployee.ToList();
foreach (var employee in employeelist)
{
// var employeeAtt = new EmployeeAtt();
var employeeAtt = _context.AttendanceTable
.GroupBy(a => a.DateAndTime.Date)
.Select(g => new
{
Date = g.Key,
Emp_name = employee.EmployeeName,
InTime = g
.Where(e => e.ScanType == "I")
.Min(e => e.DateAndTime.TimeOfDay),
OutTime = g
.Where(e => e.ScanType == "O")
.Max(e => e.DateAndTime.TimeOfDay),
});
}
return View();
}
@model IEnumerable<Attendance.Models.EmployeeAtt>
@{`enter code here`
ViewBag.Title = "AttendanceTable";
<!--Get number of days of current month-->
var DaysInmonth = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
<!--Create a CurrentName field-->
var CurrentName = "";
}
<table class="table table-bordered">
<thead>
<tr>
<th>EmpName</th>
<!--Loop all the days of month and print it-->
@for (var numb = 1; numb <= DaysInmonth; numb++)
{
<th>@numb</th>
}
</tr>
</thead>
<tbody>
<!--Loop model-->
@foreach (var emp in Model)
{
//if Name is repeated, skip
if (CurrentName != emp.Emp_name)
{
// Set Name
CurrentName = emp.Emp_name;
<tr>
<!--print employee name one time only at the start of row-->
<td>@emp.Emp_name</td>
<!--loop all days of month-->
@for (var numb = 1; numb <= DaysInmonth; numb++)
{
<td>
@{
<!--print only that date time value which is equal to current date(as it will match column header) and current employee name, else print empty-->
var GetThatDayValue = Model.Where(a => a.Date.Value.Day == numb && a.Emp_name == emp.Emp_name).FirstOrDefault();
var DD = GetThatDayValue != null ? GetThatDayValue.InTime + " " + GetThatDayValue.OutTime : "A";
<text> @DD </text>
}
</td>
}
</tr>
}
}
</tbody>
</table>
How can i convert from anonymous type to concrete type so that i can make a list of view model objects ( EmployeeAtt) and access it in my view
Why do you need the creation of anonymous objects if you can just select concrete type at the compile time?
So basically you may do this in Select:
.Select(g => new EmployeeAtt { /* fill in properties */ });
If you do not know exact type and want to convert in runtime you may try to use Convert.ChangeType
along with TypeDescriptor.GetConverter
Convert.ChangeType(TypeDescriptor.GetConverter(objectType).ConvertFrom(anonymousObject), objectType));