您的位置:首页 > 移动开发 > Objective-C

Part 29 - Using data transfer object as the model in mvc

2016-10-24 11:05 656 查看
In this video we will discuss, using data transfer object as the model in mvc. Please watch
Part 28, before proceeding. 

Let's say the business requirement is such that, we want to display total number of employees by department as shown below. At the moment, either the Employee orDepartment class
does not have Total property. This is one example, where a Data Transfer Object can be used as a model.



Right click on the "Models" folder and add a class with name="DepartmentTotals.cs". Copy and paste the following code.
public class DepartmentTotals
{
    public string Name { get; set; }
    public int Total { get; set; }
}

Now add the following "EmployeesByDepartment" controller action method toEmployeeController class.
public ActionResult EmployeesByDepartment()
{
    var departmentTotals = db.Employees.Include("Department")
                                .GroupBy(x => x.Department.Name)
                                .Select(y => new DepartmentTotals 
                                { 
                                    Name = y.Key, Total = y.Count() 
                                }).ToList();
    return View(departmentTotals);
}

At this point, build the solution, so that the newly added DepartmentTotals class is compiled.

Now right click on "EmployeesByDepartment" action method in "EmployeeController"and select "Add View" from the context menu.
View name = EmployeesByDepartment
View engine = Razor
Select "Create a strongly-typed view" checkbox
Model class = DepartmentTotals
Model class = DepartmentTotals

To list the employees in ascending order of total employee, use OrderBy() LINQ method as shown below.
var departmentTotals = db.Employees.Include("Department")
                            .GroupBy(x => x.Department.Name)
                            .Select(y => new DepartmentTotals 
                            { 
                                Name = y.Key, Total = y.Count() 
                            }).ToList().OrderBy(y => y.Total);

To sort the list in descending order use, OrderByDescending() LINQ method.
var departmentTotals = db.Employees.Include("Department")
           
aab8
                .GroupBy(x => x.Department.Name)
                            .Select(y => new DepartmentTotals 
                            { 
                                Name = y.Key, Total = y.Count() 
                            }).ToList().OrderByDescending(y => y.Total);
            return View(departmentTotals); 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: