简体   繁体   中英

Get multiple tables using Entity Framework Core

I need to populate many selectlists and i'm doing it like this

     public void OnGet()
    {
        ViewData["CelulaId"] = new SelectList(_context.Celulas, "Id", "Nome");
        ViewData["UAPId"] = new SelectList(_context.UAP, "Id", "Nome");
        ViewData["ReferenciaId"] = new SelectList(_context.Referencias, "Id", "Nome");
        ViewData["CelulaTipoId"] = new SelectList(_context.CelulaTipos, "Id", "Nome");
    }

I assume this is a poor approach because of the consecutive calls. Is there a way to do all in one go?

You can construct a query that combines all id and name fields in one query, which you can filter afterwards if you add a discriminator as well. I don't have time to test the code, but it could be something like this:

var res = _context.Celulas.Select(c => new { Id, Nome, Discriminator = "Celulas"})
    .Union(_context.UAP.Select(c => new { Id, Nome, Discriminator = "UAP"}))
    .Union(_context.Referencias.Select(c => new { Id, Nome, Discriminator = "Referencias"}))
    .Union(_context.CelulaTipos.Select(c => new { Id, Nome, Discriminator = "CelulaTipos"}));

And then pass it to the viewmodel:

var viewModel = new ViewModel
{
    CelulaId = new SelectList(res.Where(r => r.Discriminator == "Celulas"), "Id", "Nome"),
    UAPId = new SelectList(res.Where(r => r.Discriminator == "UAP"), "Id", "Nome"),
    ReferenciaId = new SelectList(res.Where(r => r.Discriminator == "Referencias"), "Id", "Nome"),
    CelulaTipoId = new SelectList(res.Where(r => r.Discriminator == "CelulaTipos"), "Id", "Nome")
};

But I doubt this is really faster than what you already have. It only adds complexity. An alternative may be to use enumerations so you don't have to query the database at all.

As a side note, I would not use ViewData for this. Instead add the lists to the ViewModel . I would use ViewData to communicate with parts that do not have access to the model, eg the title in the layout.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM