Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

How do I query a database only once?

$
0
0

I have a drop down that's populated from a database table and its corresponding model. Works great!

However, every time I return to the controller, I have to read the table again.  This seems inefficient at best.  I tried to overcome this by creating a static object, but every time a View is rendered, the object is disposed and an error is thrown by the controller.  How do I overcome this?

Here is my failed code:

// List of bagtypes. Only want to get these once
public static DbSet<Bagtypes> bagtypes {get; set;} = null;

... Other Controller code

[HttpGet]
public async Task<IActionResult> Edit(int? id, bool? copy)
{

// other edit stuff here


if (bagtypes == null) // Only do this the first time through...

{

bagtypes = _db.Types;

}

bvm.TypeOfBag = bagtypes;

return View(bvm);

}


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>