应用程序中断访问dbcontext,Asp .net核心web api 2.0与实体框架核心2.0数据库的第一种方法

bha*_*a.m 7 entity-framework-6 entity-framework-core asp.net-core-mvc asp.net-core asp.net-core-webapi

我用EntityFrameworkCore.SqlServer 2.0开发了asp .net核心wep api 2.0应用程序.它是使用数据库第一种方法开发的.当尝试使用dbcontext访问实体时,应用程序将进入中断模式.我找不到应用程序状态进入中断状态的原因.请帮忙解决这个问题.

下面是DBContext类中的OnConfiguring方法.

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer(@"Server=(local);Database=VotingAppDB;User ID=sa;Password=123;");
        }
    }
Run Code Online (Sandbox Code Playgroud)

下面的代码块用于访问控制器中的dbcontext实体

    // GET api/values
    [HttpGet]
    public IEnumerable<string> Get()
    {
        VotingAppDBContext context = new VotingAppDBContext();
        var questions = context.Questions.ToList();
        return new string[] { "value1", "value2" };
    }
Run Code Online (Sandbox Code Playgroud)

已安装的包裹

应用程序错误

Jua*_*uan 2

1.- First of all you shouldn't create a context inside the controller, avoid use 'new' with dependencies because that would make your code untestable, in my case as I use UnitOfWork I inject it as IUnitOfWork instance that is, indeed, an extension of MyConext, and you'd inject it within the StartUp class... To do so I have a private method (to perform this in a single private call) that looks like:

 private void AddEntityFrameworkAndDbContext(IServiceCollection services)
        {
            services.AddEntityFrameworkSqlServer();

            var migrationsAssemblyName = typeof(MyContext).GetTypeInfo().Assembly.GetName().Name;
            services.AddDbContext<MyContext>(options =>
            {
                options.UseSqlServer(
                    "MY CONNECTION STRING GOES HERE (BUT I RETREIVE IT FROM ANOTHER SERVICE)",
                    sqlServerOptionsAction: sqlOptions =>
                    {
                        sqlOptions.MigrationsAssembly(migrationsAssemblyName);
                        sqlOptions.EnableRetryOnFailure(maxRetryCount: 5, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
                    });
            },
            ServiceLifetime.Scoped  // Showing explicitly that the DbContext is shared across the HTTP request scope (graph of objects started in the HTTP request)
                   ).AddUnitOfWork<MyContext>(); // This is because I'm also using EF Core Unit of work NuGet Package
        }
Run Code Online (Sandbox Code Playgroud)

I'm calling that private method from ConfigureServices(IServiceCollection services), as I said, in StartUp class

        // Add EF, and UoW
        AddEntityFrameworkAndDbContext(services);
Run Code Online (Sandbox Code Playgroud)

2.- Secondly (but I'd say that this is your real problem) I'd say that you missed base.OnConfiguring(options); in your context, it should be like:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer(@"Server=(local);Database=VotingAppDB;User ID=sa;Password=123;");
        }
        base.OnConfiguring(optionsBuilder);
    }
Run Code Online (Sandbox Code Playgroud)

另外,请看看我几周前写的这个答案: How to setup EF6 Migrations with ASP.NET Core

此外,UnitOfWork 项目值得一读,请在这里查看: https: //github.com/arch/UnitOfWork

我希望它有帮助,

胡安