I’ve got a .NET MVC app where I need to display a list of images with some text. The images and text are stored in the database in the same table, and returned in my simple model. What I haven’t figured out is how to display all of these images without hitting the database again for every single image.
I see several examples, such as:
- ASP.NET MVC: loading images from database and displaying their in view
- Problem with displaying image from DB using asp.net MVC 2
and others, but they all go back to the database for every image. That doesn’t make sense, because there could be dozens of images, and I don’t want to keep making single calls to the database when I already have the image data returned in my model.
I’m new to ASP.NET MVC, (and also never worked with images stored in a DB before) and I think I am just missing something, and that it can’t be this difficult. If anyone has solved this, I’d love to hear it, and I think others would too, based on the other questions already here.
Just hit the database multiple times. I once thought it was a clever idea to load the images together with the text in the cache and then invalidate the cache when they were served. I also had to generate random URLs to avoid different users invalidating each others cache. I thought it was so clever to reduce the number of DB queries.
I am now so ashamed by this “cleverness” and I don’t tell anybody. Don’t think about it unless you have actual performance problem.
It is important to implement client side caching by setting the appropriate headers. Images are better cached on the client than on the server because even if you cache on the server you still take the network transfer hit if you do not cache on the client.
Also hitting the database by primary key (I assume this is how you are going to retreive images) is not an expensive operation and unless the images are 2MB+ I wouldn’t worry about transfer from the database to the web server either.
Edit: And I just told everybody about my shame 🙁