Search code examples
entity-framework-coreviewmodeldbcontextasp.net-core-2.1

How to access DbContext in viewmodel with AspNetCore 2.1?


Using DropDown input fields is very common when you want to display a description while saving an ID in your database. If I consider my Person model, I have PersonViewModel which has a SelectList used to display a list of possible Job Descriptions

    public SelectList SelectJobDescription
    {
        get
        {
            MyDbContext _context = new MyDbContext();
            var result = new SelectList(_context.Keywords
                                    .Where(k => k.Name == ".JobDescription")
                                    .OrderBy(r => r.Valuename), "Valuecode", "Valuename");
            _context.Dispose();
            return result;
        }
    }

and I use this SelectList in my create/edit views like this:

        <div class="form-group row">
            <label asp-for="JobDescription" class="col-sm-4 col-form-label"></label>
            <div class="col-sm-8">
                <select asp-for="JobDescription" asp-items="@Model.SelectJobDescription" class="form-control">
                    <option>Select a Job Description</option>
                </select>
        </div>

Is it correct to use _context this way in the ViewModel or there is some other way to do the same thing better (maybe DI?)


Solution

  • Set the property after instatiating the view model (or during initialization), for example:

    var vm = new YourViewModel()
    {
        SelectJobDescription = new SelectList( _context... ),
    };
    
    return View( vm );