我正在尝试配置一个新项目,使用
这是我所做的(我有两个项目,一个是
ASP.net Core
和Entity Framework 6
。为了能够使用Entity Framework 6
,我使用了完整的.net
框架。这是以前在MVC中的一个项目,我需要将其迁移到Core。这是我所做的(我有两个项目,一个是
Asp.net Core
,另一个是包含一些类和DBContext类
的class library
):
appsettings.json
:
"Data": {
"ConnectionStrings": {
"MyConnection": "Server=namedatabase.database.secure.windows.net,1433;Database=database_Name;User ID=blahblah;Password=blahblah;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"
}
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<MyDBContext>(_ => new LIGDataContext(Configuration.GetConnectionString("MyConnection")));
}
我将DBContext
类单独放在一个类库(.dll)
中:
public class MyDBContext: DbContext
{
public MyDBContext(string connString): base(connString)
{
}
但我把这些代码放在我的asp.net Core
项目的一些控制器中,现在不确定如何引用DBContext
实例... 显然正在请求connString
参数,这是我第一次这样做,不确定最好的方法是什么,在Core
中不再可用ConfigurationManager
,我需要做什么?这是Entity Framework 6而不是Entity Framework Core。
public class MyController : Controller
{
public ActionResult MyAction()
{
var _ctx = new MyDBContext();
return PartialView(_ctx.FormsiteApplications.Where(f => f.Application).OrderBy(f => f.Title).ToList());
}
services.AddScoped<MyDBContext>(_ => new LIGDataContext(Configuration.GetConnectionString("MyConnection")));
配置在ConfigureServices()
中注入 DbContext。有没有不让 DbContext 通过属性注入到控制器中的原因(您正在实例化它var _ctx = new MyDBContext();
)?我认为这应该可以工作。 - dime2lo