0

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?

Apuna12
  • 375
  • 2
  • 6
  • 23
  • 1
    take a look at background services https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-5.0&tabs=visual-studio – Svyatoslav Ryumkin Oct 25 '21 at 09:43
  • 1
    How do you want to actually trigger this? Normally a data transfer is triggered on a schedule or on some other specific trigger. It is very unusual to trigger a data transfer on a web application startup. How often should this data actually be transferred? It seems like you are trying to use a web application to do data integration. – Nick.Mc Oct 27 '21 at 12:26
  • Descriptions like "with no luck" imply that you haven't analysed how it actually failed. You'll need to do that to be able to describe in what way it failed. – Nick.Mc Oct 27 '21 at 12:27

1 Answers1

2

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:

George Birbilis
  • 2,782
  • 2
  • 33
  • 35