简体   繁体   中英

How to configure Entity Framework 6 for ASP.net Core

I'm trying to configure a new project to use Entity Framework 6 with ASP.net Core , I'm using the full .net framework in order to be able to use Entity Framework 6 . This is a project that was in MVC before and I need to migrate it to Core. This is what I've done(I have two projects, one Asp.net Core and a class library that contains some classes and the 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;"
    }
  }

Startup.cs

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

I have the DBContext class separated in a class library(.dll) :

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

But I have this code inside some controllers of my asp.net Core project and I'm not sure how to refer now to the DBContext instance... Clearly is asking for the connString parameter, this is the first time I'm doing this and I'm not sure which is the best approach to do this, ConfigurationManager is not available anymore in Core what do I need to do? This is Entity Framework 6 no 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());
              }

dime2lo is right, you can inject the DbContext to the controller.

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

or create a context factory

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM