Is there a way to keep the enums from the database?

I am new to ASP.NET, experienced with WinForms and WPF. Take it easy on me.

When my page loads, it hits the database and asks for a table to select from the dropdown. Now if you do a postback on the page, reload the values ​​in form_load? It seems unnecessary to hit the database twice. My guess is that I was putting form_load, I was hitting the database for enums, and then filling in the dropdowns I found.

+2


source to share


4 answers


I am assuming you are talking about a "lookup table", basically something that has a schema {Id, Name} and is referenced as a foreign key from another table, right?

This is an age old question, and there is no "right" answer.

If your enum is likely to change at all (it might be controlled by an administrative user), you won't be able to use @Andrei Rinea's suggestion, since you will need to update the value from the database. Ultimately, you will be better off doing what Keltex suggests and copying the results with a short expiration date - perhaps as little as 5 minutes. Just a small amount of caching can significantly improve performance if you are under heavy load.



If your enum is unlikely to change ... especially if it is not modified through the admin UI, there is an interesting trick I like to do, namely mapping an enum to an actual C # enum with a value enum

tied directly to the primary key of the enum table. This way, you never have to hit the database to get a list of possible values.

The downside to this trick is that a new enum member requires a fresh compilation of your code and a new deployment. It may or may not be perfect, so use the trick with care.

+1


source


You control what is called during postbacks with the Page.IsPostBack Property. It returns a boolean indicating when the page is in postback. Example:




public partial class _Default : System.Web.UI.Page {
    protected void Page_Load(object sender, EventArgs e) {
        if (!this.IsPostBack) {
            // fill the enums
        }
    }
}


      

+2


source


Use an object Cache

and store the database results in the cache.

+2


source


They can be loaded at application startup in the Application object. I guess they will not change too often.

Then used from there. For those "catalogs" that rarely change (once a year or less), I often code them into an enumeration type as well.

Edit:

For enums like PaymentStatus or those that are rarely or never listed are listed in the directory with the same numerical values, as Randolfo said. For other caches in the HttpRuntimeCache object ("Cache") and place either an absolute expiration or a SqlDependency

+1


source







All Articles