问题描述
我正在尝试从ASP.NET Core 1.0 MVC项目中的模型内与数据库进行交互.脚手架已被用来从模型中创建控制器和视图.
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.
理想情况下,我想像使用_context在控制器中一样访问它,但是我找不到这样做的方法.
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
}
但是ApplicationDbContext构造函数需要选项参数,例如我无法从配置中检索到的默认连接字符串.
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.
有什么想法吗?
推荐答案
正如其他人告诉您的那样,方法是使用依赖项注入.
As others have told you, the way is use dependency injection.
这是一个真实的示例(使用postgresql):
Here is a real example (using postgresql):
Startup.cs:
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
...
}
在您的控制器中(例如api控制器):
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.(...);
...
}
}
这里有一个完整的示例(您可以向下滚动到创建数据库上下文"): https://docs.microsoft.com/zh-CN/aspnet/core/data/ef-mvc/intro
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
希望有帮助.
这篇关于在ASP.NET Core MVC模型中访问_context的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!