Asp.Net Core 3.1 MVC Run the query only once when running the program?

AliKhansari

I want to write a query When the program first runs, query Add values ​​to the database?

I want this query to run only once

What is the best solution?

Brando Zhang

As far as I know, if you want to run dbcontext when the application started, I suggest you could try to asp.net core lifetime method to run codes in the Configure method.

More details, you could refer to below codes:

In the startup.cs Configure method add below codes:

        lifetime.ApplicationStarted.Register(
         () => AddLogs(app));

Addlogs method:

    static void AddLogs(IApplicationBuilder app)
    {

        using (var serviceScope = app.ApplicationServices.CreateScope())
        {
            //Check the table or role is exsited or not to make sure below codes will just start once.
            if (true)
            {

                var context = serviceScope.ServiceProvider.GetService<TestDbcontext>();

                var list = context.Admissions.ToList();
                //dbcontext.Admissions.Add(new Admission() { });
                context.SaveChanges();
            }

        }
    }

Result:

enter image description here


Update:

lifetime is a parameter which we could passed to the startup.cs Configure method:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime lifetime)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

InvalidOperationException when using select query in ASP.NET Core MVC

What happens of Program.Main when an ASP.NET Core application is run on IISIntegration?

Getting IMetadataDetailsProviders to Run More than Once in ASP.NET Core

Validating two attributes at once in ASP.NET Core MVC

ASP.NET MVC 4 ViewBag value incremented only once

ASP.NET MVC 5 - redirect from view only once

How to show a page only once in asp.net mvc

The model directive may only occur once per document (adding buttons to lists problem) ASP.NET MVC Core C#

Why is ASP.NET Core executing a custom middleware only once?

ASP.NET Core populate model only once for all views

run insert query once only when the database is created php pdo

.ASP.NET Core only run policy handler when policy exists on controller

With google auth, how do I setup asp.net core to request https redirects when asp.net core is running http only, but reverse proxy runs https only?

Run ASP.NET Core App in Docker Running as Custom User

ASP.NET Core 3 EF Framework - transient failure when running lots of queries

the program is not able to find handler for MediatR query ASP.Net Core

run asp.net core mvc Application in visual Studio code

Database query returning only the first element of the data base as the same instance for all, in ASP.NET MVC Core 6

Only accept local request in ASP.Net Core 2.1 MVC

LINQ query returning NULL ASP-NET-CORE MVC

LINQ Query not working properly ASP.NET CORE MVC

ASP.NET Core MVC Group by query with LINQ

How to IEnumerable query in ASP.NET Core MVC?

NHibernate on Mono running ASP.NET MVC 3 web application

Ajax query for script loading is running only once

Running ASP.NET Core MVC as a Console Application Project without .NET Core SDK

Running ASP .NET Core on Raspbery Pi 3 B+

Script in if-up.d appears to be running 3 times. Only want it to run once

When to use ResultFilter in ASP.NET core MVC

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    pump.io port in URL

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

  14. 14

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  15. 15

    How to use merge windows unallocated space into Ubuntu using GParted?

  16. 16

    flutter: dropdown item programmatically unselect problem

  17. 17

    Pandas - check if dataframe has negative value in any column

  18. 18

    Nuget add packages gives access denied errors

  19. 19

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  20. 20

    Generate random UUIDv4 with Elm

  21. 21

    Client secret not provided in request error with Keycloak

HotTag

Archive