Part 29 Using data transfer object as the model in mvc

preview_player
Показать описание
In this video we will discuss, using data transfer object as the model in mvc. Please watch Part 28, before proceeding.

Healthy diet is very important both for the body and mind. If you like Aarvi Kitchen recipes, please support by sharing, subscribing and liking our YouTube channel. Hope you can help.

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

public class DepartmentTotals
{
public string Name { get; set; }
public int Total { get; set; }
}

Now add the following "EmployeesByDepartment" controller action method to EmployeeController 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")
.GroupBy(x =] x.Department.Name)
.Select(y =] new DepartmentTotals
{
Name = y.Key, Total = y.Count()
}).ToList().OrderByDescending(y =] y.Total);
return View(departmentTotals);

Text version of the video

Slides

All ASP .NET MVC Text Articles

All ASP .NET MVC Slides

All Dot Net and SQL Server Tutorials in English

All Dot Net and SQL Server Tutorials in Arabic
Рекомендации по теме
Комментарии
Автор

Hi, sure, I will definitely record videos on the concepts you mentioned as soon as I can. Thank you very much for taking time to give feedback. I am really glad you found these videos useful. May I ask you for a favour. I want these tutorials to be helpful for as many people as possible. Please free to share the link with your friends and family who you think would also benefit from them. If you like these videos, please click on the THUMBS UP button below the video. Good Luck.

Csharp-video-tutorialsBlogspot
Автор

Thank you very much sir,
I have one request, Can you please add some videos on manual AJAX and jQuery AJAX,
Your explanation is very simple and understandable.You really make it simple to grasp. Thank you so Much.

a
Автор

Hi Venkat,
Generally In group by clause we can use multiple columns. If we use multiple columns in Group By how to make use of "Key" concept ?

If we have only one column in Group by we can use "Key" Property like below. How can I use that "Key" Property if we have multiple columns in Group By Clause..?

=> X.Department.Name).Select(y => new DepartmentTotals
{
Name = y.Key,
Total = y.Count()
})

Regards
Venkat Avula

VenkatAvula
Автор

Hey Venkat! Can you show me that example using the linq query syntax. It will really help me.

jyotiagarwal
Автор

I had the same problem generating the View for EmployeeByDepartments()
I have just added :
[Key]
public int id { get; set; }
property in DepartmentTotals class
and I have got the View

georgenistor
Автор

hello add [key] in DepartmentTotals Model




public class DepartmentTotal
{
[Key]
public string Name { get; set; }

public int total { get; set; }
}

RoshanSingh-lgnz
Автор

on your blog, could you change the last step in the add view part? it should say "list". that step threw me. thanks for the great work

MrHooglaz
Автор

Overwhelmed with errors causing me to spend more time ironing out bugs than learning. Using Visual Studio Community 2013 with these problems:
* No recognition of DepartmentTotals class when typing in the EmployeesByDepartment() method, so I added: using MVCDemo4.Models; to the top.

When adding the view, which uses a totally different window now, I put
Template: "List",
Model Class: "EmployeeMetaData (MVCDemo4.Model),
Data context class: "EmployeeContext(MVCDemo4)
and checked options: Reference Script Libraries and Use a Layout Page. 
When I Add,  I get error: "Unable to retrieve metadata for One or more validation errors were detected during model generation:  

EmployeeMetaData:  : EntityType ' EmployeeMetaData has no key defined. Define the key for this Entity Type. EmployeeMetaDatas: EntitySe ' EmployeeMetaDatas' is based on type 'EmployeeMetaData' that has no keys defined.'

dmccalldds
Автор

Hello Venkat, your project did't work in my computer, I added AsEnumerable() before Select (in 1:32), after that it worked. Please tell me why it did't work in my PC. I Use VS 2015.
Error was like this "The entity or complex type cannot be constructed in a LINQ to Entities query." Thanks a lot.

remodabashyan
Автор

Sir i am learning mvc 5. when i am adding scaffolding template it show error "Unable to retrieve metadata for ". please tell me how to resolve this error or provide me steps to resolve this issue.

profajaysharma
Автор

Hi is it good practice to access data directly from the controller class using the dbcontext or should we have a business object layer (which you used in your earlier examples) Many thanks.

Will-kckx
Автор

How to fetch dropdown selected value from view in controller to add ModelState error as we added for textbox values for being null?
Ex:When we are creating an Employee if the user selects "Select Department" value from Department dropdown list, we need to add the error stating "Please select the valid Department".
How do we achieve this?
Help is much appreciated...

Thanks...

vijethamm
Автор

Part 29. While adding view for empby dept getting error as class has no defined key, define the key for this entity type. I am using VS 2015.Any solution?

abhisheksutar
Автор

Sir... I have a question for you. Why you are still using Windows 7? Is windows 10 wont support some apps? I don't know exactly. Please tell me.

krishnapraveen
Автор

can you help me plz ? i don't know how pass data from entity to DTO ?

reyhanehsh
Автор

It is giving error unable to retrieve metadata'EntityModel.Models.DepartmentTotal, while creating view(doing it with visual studio 2013)

bijoybhaskar
Автор

Hello Sir, please Upload a Video on Proper Signout in ASP.NET, Thank You So much

siva
Автор

how to list total department list here with if no employee are asscociated with that department, mark zero(0)

NaveenSinhamyprofile
Автор

Hi venkat this is not working when i am creating view it says that DepartmentTotal Class not contain primary key and i solved by add [Key] annotation but it will display following error

Microsoft Visual Studio

Error

There was an error running the selected code generator:

'Unable to retrieve metadata for '

OK

kaushalbhatt
Автор

Anyone getting the issue while Adding the View for EmployeesByDepartment in VS2013, Delete the Text from Data Context Class dropdown. It will work after that.

adeebjalalkhan
welcome to shbcf.ru