Question

Am trying to figure this out.

I have a major class called Foods.

I have multiple classes that inherit from Food: Pizza, Sandwich, Meals etc...

I created the database using Code First Approach. The database has tables for Pizza, Sandwich and meals.

Now on my homepage, I need to display top 5 of each of the foods i have, but i dont wanna create a table called foods. So how do i get the list of the top 5 foods (i dont have access to foods.ToList() from my DBSet class since that will incur me to create a database table for it, still how do i get all these values into multiple objects of the Class Foods. and then pass them to the view in my C# code?

After i get all these values of top 5 pizzas, top 5 sanwiches, top 5 meals, i then pass need to pass them to a partial view that renders the model "foods" and displays the properties that are common between those classes (i.e. only the ones that are in foods and not the specialty properties of the single ones in pizza or meals) etc...

This is important as i am trying to understand the concept of how mvc works, and this is different from creating a class of 2 models and creating a view that accepts this model that has lets say pizza and sandwiches together as i see in all the posts online.

Was it helpful?

Solution

This case seems like a great opportunity to use the Repository Pattern. With this pattern, you could create a class called "FoodRepository" which could read from your DbSets for the specific tables, wrap them in the parent "Food" class, and return them as a list. This repository would contain all the logic for doing things like the "Top 5 Food". The controller would make a call to this repository, and return this List in the View Model. The View would then pass this to a partial view that is strongly-typed to a IEnumerable and would be responsible for displaying that list.

Here is a great tutorial on getting started using the Repository Pattern with EF Code First.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top