2016-11-09 39 views
3

我想配置一個新項目使用Entity Framework 6ASP.net Core,我正在使用完整的.net框架,以便能夠使用Entity Framework 6。這是一個MVC之前的項目,我需要將它遷移到Core。 這是我做了什麼(我有兩個項目,一個Asp.net Core和含有一些類和DBContext class一個class library):如何配置實體框架6爲ASP.net核心

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類的class library(.dll)分離:

public class MyDBContext: DbContext 
    { 
public MyDBContext(string connString): base(connString) 
     { 
     } 

但我有我的asp.net Core項目的某些控制器內部此代碼,我不知道現在該怎麼指DBContext實例......顯然是要求connString參數,這是我第一次這樣做,我不確定哪個是最好的方法來做到這一點,ConfigurationManager不再可用Core我需要做什麼?這是實體框架6無實體框架核心..

 public class MyController : Controller 
     { 
      public ActionResult MyAction() 
       { 
        var _ctx = new MyDBContext(); 
        return PartialView(_ctx.FormsiteApplications.Where(f => f.Application).OrderBy(f => f.Title).ToList()); 
       } 
+1

要配置的DbContext的噴射在'ConfigureServices()'用'services.AddScoped (_ =>新LIGDataContext(配置.GetConnectionString( 「MyConnection的」)));'。任何不讓DbContext通過屬性注入Controller的理由(你正在實例化它'var _ctx = new MyDBContext();')?我認爲它應該工作。 – dime2lo

回答

0

dime2lo是正確的,您可以注入DbContext到控制器。

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

或創建上下文工廠

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

Reference : Getting Started with ASP.NET Core and Entity Framework 6