如何为 ASP.net Core 配置实体框架 6

Ale*_*xGH 6 c# asp.net asp.net-mvc entity-framework asp.net-core-mvc

我正在尝试配置一个新项目来使用Entity Framework 6ASP.net Core我正在使用完整的.net框架以便能够使用Entity Framework 6. 这是一个以前在MVC中的项目,我需要将其迁移到Core。这就是我所做的(我有两个项目,一个项目Asp.net Core和一个class library包含一些类和DBContext class):

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;"
    }
  }
Run Code Online (Sandbox Code Playgroud)

Startup.cs

 public void ConfigureServices(IServiceCollection services)
        {
         services.AddScoped<MyDBContext>(_ => new LIGDataContext(Configuration.GetConnectionString("MyConnection")));
        }
Run Code Online (Sandbox Code Playgroud)

我将DBContext班级分开class library(.dll)

  public class MyDBContext: DbContext
    {
 public MyDBContext(string connString): base(connString)
        {
        }
Run Code Online (Sandbox Code Playgroud)

但是我的asp.net Core项目的一些控制器中有这段代码,我不知道现在如何引用该DBContext实例...显然是在询问connString参数,这是我第一次这样做,我不确定这是执行此操作的最佳方法,但我需要做什么不再可用ConfigurationManagerCore这是 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());
              }
Run Code Online (Sandbox Code Playgroud)

The*_* JB 0

dime2lo 是对的,您可以将 DbContext 注入到控制器中。

codepublic class StoreController : Controller
{
    private DefaultDbContext _dbContext = null;
    public StoreController(DefaultDbContext dbContext)
    {
        this._dbContext = dbContext;
        //Do something with this._dbContext ...
    }
}
Run Code Online (Sandbox Code Playgroud)

或创建一个上下文工厂

public class DefaultDbContextFactory : IDbContextFactory<DefaultDbContext>{
public DefaultDbContext Create()
{
    return new DefaultDbContext("Server=XXXX ;Database=XXXXX;Trusted_Connection=True;");
}
Run Code Online (Sandbox Code Playgroud)

参考:ASP.NET Core 和 Entity Framework 6 入门