I have the following data structure in my database:
LastName FirstName CourseName
John Day Pricing
John Day Marketing
John Day Finance
Lisa Smith Marketing
Lisa Smith Finance
etc...
The data shows employess within a business and which courses they have shown a preference to attend. The number of courses per employee will vary (i.e. as above, John has 3 courses and Lisa 2).
I need to take this data from the database and pass it to a webpage view (asp.net mvc).
I would like the data that comes out of my database to match the view as much as possible and want to transform the data using SQl so that it looks like the following:
LastName FirstName Course1 Course2 Course3
John Day Pricing Marketing Finance
Lisa Smith Marketing Finance
Any thoughts on how this may be achieved?
Note: one of the reasons I am trying this approach is that the original data structure does not easily lend itself to be iterated over using the typical mvc syntax:
<% foreach (var item in Model.courseData) { %>
Because of the duplication of names in the orignal data I would end up with lots of conditionals in my View which I would like to avoid.
I have tried transforming the data using c# in my ViewModel but have found it tough going and feel that I could lighten the workload by leveraging SQL before I return the data.
Thanks.
NOTE: I don’t want to use the Database PIVOT feature because the number of classes will most likely change and you have to update your SQL query.
What you are trying to do should not be done in the View.
The Model object should be simple enough to be rendered when passed to a View.
Because, the View shouldn’t have any complicated logic in it.
Therefore, we need to pre-process the data returned from the SQL Server Database first.
I am going to assume that you have an object like this because you didn’t mention it has a unique identifier like “CustomerId” or something.
This is going to be my [Model] object.
This is my Action method in the Controller.
I aggregated the data into a Data Structure that is easier to render.
I intentionally added [MaxCourseCount] property to my Model object because it seems like you want to render the Course Data in a <table> format.
So, all you need to do now is
I hope this helps.
-Soe