About Entity Framework
Entity Framework is an Object Relational Mapping (ORM) Framework. It enables us to create classes from relational database tables and vice versa is also possible (i.e., sql tables from classes). Thus it enables developers to deal with the data in the database as objects and properties. Using the Entity Framework, developers issue queries using LINQ, then retrieve and manipulate data as strongly typed objects.
There might be many situations where one needs to sum the data that is retrieved using Entity Framework. For Example in enterprises, manager checks the employee’s timesheet regularly in order to track their working hour’s weekly/monthly. Employee fills his timesheet daily. So we need to sum up the daily employee time for a given week/month to present it to the manager.
This particular blog looks at grouping data by month in MVC 5 with Entity Framework 6.0.
Firstly create sample database and name it as “EmpTimeSheetDB” and then create table “EmployeeTimeSheet” with some sample relevant data in it as below
Create new MVC5 project and then create .edmx file which points out to our already created database “EmpTimeSheetDB” .
Create an object for db context class.
Get the data from the table and convert to list.
As we are populating the data for the employee month so, from the list we need to filter data for a given month using linq query.
Now, it’s time to group the data using employee id and name using LINQ GroupBy operator.
LINQ stands for Language Integrated Query . LINQ GroupBy is a different and Unique in its way. This takes a collection of items as input, and then groups the items based on any particular property of the item, which is common between all the items.
Here we used Sum function to sum up the employee working hours. For that initially sum hours and minutes individually for getting the actual total worked hours for a given month as above.
To get the projects worked by employee for a given month use join function, this helps to separate the list of projects with a delimiter.
And the final EmployeesTimesheet for the month of January.
Within Linq query we cannot do any C# datatype conversions. So we have firstly converted the IQueryable object that is returned by linq query to IEnumerable. And then on this list we have performed all the conversions.
Pixentia is an enthusiastic family of individuals, fervent to make lives simpler through effective use of technology. Our mission is to implement solutions that drives business results. Know more insights from our thoughts and experience.
Contact us today or call 1-855-978-6816 to talk with us about your business needs.