Apuna12
Apuna12

Reputation: 239

Executing DB Update on Startup in ASP .Net Core MVC

I am working on an application that should take data from one server and put the data into my database. I am currently struggling to update the database on startups.

I tried several approaches like creating an action which is calling a model which updates the database (with no luck), I tried to research if there is a way to do it in Startup class, but again with no luck.

I have these methods for now

TfsMethods.cs (Models class)

    public TfsMethods(ApplicationDbContext db)
    {
        _db = db;
    }

    public void UpdateDbBranches()
    {
        var branches = GetAllBranches();
        var dbBranches = _db.Branches;
        foreach (var branch in branches)
        {
            if (dbBranches.Where(x => x.BranchName == branch.BranchName) == null)
            {
                _db.Add(branch);
            }
        }
    }

where _db is ApplicationDbContext and GetAllBranches() is a method which gets data from one server and I want to put these into my DB.

BranchController.cs (Controller class)

public IActionResult UpdateDbBranches()
    {
        TfsMethods tfs = new TfsMethods( _db );
        try
        {
            tfs.UpdateDbBranches();
            return Ok();
        }
        catch( Exception e )
        {
            return Problem( e.ToString() );
        }
    }

The issue here is that I don't know what to call it on startups, even on razor page or Startup.cs

Is this somehow possible or is there any implementation that could help me with this issue?

Upvotes: 0

Views: 1568

Answers (1)

George Birbilis
George Birbilis

Reputation: 2930

There are several useful answers already available at: Application startup code in ASP.NET Core

However, you should first consider if you really want to do this on startup or on a schedule. See Quartz.net for example: https://www.infoworld.com/article/3529418/how-to-schedule-jobs-using-quartznet-in-aspnet-core.html

If you're trying to do so-called Database Seeding, these links (and links in those discussions) may be useful to you:

Upvotes: 2

Related Questions