0

I have a C# MVC 5 web application which I have created a model that contains categories and then I used the automatically created controller and views via MVC 5 Controller with views, using Entity Framework.

I have several other controls that need a list of those categories. The list of categories is needed at least once per page but sometimes multiple times. Instead of doing multiple database calls, I just read the information into a list, like this:

var categoryQuery = from d in db.Categories
                    orderby d.Name
                    where d.Visible == true
                    select d;
List<Category> categoryList = new List<Category>();
categoryList.AddRange(categoryQuery);

Is there somewhere in my controller that I can put this code so that it is called only once but then I can use the list multiple times?

Edit:

Editing to provide a better example. In my _Layout.cshtml page, I call an HTML action which returns a partial view to display the category list:

@Html.Action("Menu", "Categories", new { DropdownMenuTitle = "Categories" })

Then on my Index.cshtml page, in the same controller, I do another database call to get a list of the categories which I create a SelectList and then a DropDownList on the page.

How do I do this without the two database calls?

user1624184
  • 141
  • 11
  • Are you turning off [tag:entity-framework]'s caching? If not, then the results should be cached already (referring to: multiple times per page). – Erik Philips Dec 15 '15 at 06:19
  • When you navigate to a page a new instance of a controller is created, so putting the code in a controller will still mean your database is called each time. You can cache it somewhere if its unlikely to change. –  Dec 15 '15 at 06:19
  • Since it looks like the data you are interested in is not "per-user", linked duplicate that talks about caching should provide you good solution. If you just need it cache value for multiple controls on single page please clarify why can't you have one copy of the data in your action (edit post so it can be re-opened in this case). – Alexei Levenkov Dec 15 '15 at 06:24

0 Answers0