Access _context in an ASP.NET Core MVC Model

淺唱寂寞╮ 提交于 2019-12-11 00:15:01

问题


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?


回答1:


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://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/intro

Hope it helps.



来源:https://stackoverflow.com/questions/45462139/access-context-in-an-asp-net-core-mvc-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!