【问题标题】:How to configure Entity Framework 6 for ASP.net Core如何为 ASP.net Core 配置 Entity Framework 6
【发布时间】:2017-03-23 20:06:54
【问题描述】:

我正在尝试配置一个新项目以使用Entity Framework 6ASP.net Core,我正在使用完整的.net 框架以便能够使用Entity Framework 6。这是一个之前在 MVC 中的项目,我需要将它迁移到 Core。 这就是我所做的(我有两个项目,一个Asp.net Core 和一个包含一些类的class libraryDBContext 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")));
        }

我将DBContext 类分隔在class library(.dll) 中:

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

但是我在我的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());
              }

【问题讨论】:

  • 您正在使用services.AddScoped&lt;MyDBContext&gt;(_ =&gt; new LIGDataContext(Configuration.GetConnectionString("MyConnection"))); 配置ConfigureServices() 中的DbContext 注入。有什么理由不让 DbContext 通过属性注入控制器(您正在实例化它var _ctx = new MyDBContext();)?我认为它应该有效。

标签: c# asp.net asp.net-mvc entity-framework asp.net-core-mvc


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2017-09-30
    • 2017-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-16
    • 2023-04-09
    • 2017-04-04
    相关资源
    最近更新 更多