Jerome
Jerome

Reputation: 31

Access _context in an ASP.NET Core MVC Model

I'm trying to interact with the database from within a Model in an ASP.NET Core 1.0 MVC project. Scaffolding has been used to create Controllers and views from the Models.

Ideally I would like to access it like I would in a controller with the _context but I failed finding a way to do so.

I also tried to create a new connection from the model:

using (var context = new ApplicationDbContext()){
    // Code here
}

But the ApplicationDbContext constructor requires options arguments like the default connection string which I failed retrieving from the config.

Public ApplicationDbContext(DbContextOptions options) : base(options) {
}

My guess is that I misunderstand something very basic because this should be easy to do.

Any thoughts?

Upvotes: 3

Views: 6991

Answers (1)

bruno.almeida
bruno.almeida

Reputation: 2896

As others have told you, the way is use dependency injection.

Here is a real example (using postgresql):

Startup.cs:

    public void ConfigureServices(IServiceCollection services)
    {
        ...

        #region PostgreSQL
        var sqlConnectionString = Configuration.GetConnectionString("your connection string name");

        // Use a PostgreSQL database
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseNpgsql(
                sqlConnectionString,
                b => b.MigrationsAssembly("Your.Assembly.Name")
            )
        );
        #endregion

        ...
    }

In your controller (example of an api controller):

[Produces("application/json")]
[Route("api/MyController")]
public class MyController : Controller
{

    private readonly ApplicationDbContext _context;

    public DatasourceDataController(ApplicationDbContext context)
    {
        _context = context;
    }

    [HttpGet()]
    public async Task<IActionResult> DoSometing()
    {
        ...
        await _context.(...);
        ...
    }
}

Here you have a full example (you can scroll down to "Create the Database Context"): https://learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/intro

Hope it helps.

Upvotes: 3

Related Questions