【问题标题】:InvalidOperationException: No database provider has been configured for this DbContext.InvalidOperationException:没有为此 DbContext 配置数据库提供程序。
【发布时间】:2018-05-25 21:23:57
【问题描述】:

使用 entityframeworkcore 2.03 .net core 构建一个 web api

不断收到以下错误尝试了我能想到的一切以克服它不确定是什么问题有没有其他人有这个问题?

InvalidOperationException:未配置数据库提供程序 对于这个 DbContext。可以通过覆盖来配置提供程序 DbContext.OnConfiguring 方法或通过使用 AddDbContext 上 应用服务提供商。如果使用了 AddDbContext,那么也 确保您的 DbContext 类型接受 DbContextOptions 构造函数中的对象并将其传递给基构造函数 数据库上下文

startup.cs

using churchy.Repository;
    using churchy.Service;
    using churchy.Service.Abstractions;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;

namespace churchy
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            // Database connection
            services.AddDbContext<ChurchContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("ChurchConnection")));

            // Repositories
            services.AddScoped<IRepository, Repository.Repository>();
            services.AddScoped<IRepositoryFactory, RepositoryFactory>();

            // Services
            services.AddScoped<IChurchService, ChurchService>();

            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }
    }
}

churchcontext.cs

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.EntityFrameworkCore;
using churchy.Model;


namespace churchy.Repository
{
    public class ChurchContext: DbContext
    {
        public ChurchContext()
        {
        }

        public ChurchContext(DbContextOptions<ChurchContext> options) : base(options)
        {
        }


        public DbSet<Church> Churches { get; set; }
        public DbSet<Location> Locations { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Church>().ToTable("Church");
        }
    }
}

Repository.cs

using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Threading.Tasks;

namespace churchy.Repository
{
    public class Repository : IRepository
    {
        private readonly ChurchContext _context;

        public Repository()
        {
            _context = new ChurchContext();
        }

        public IQueryable<T> GetAll<T>() where T : class
        {
            return  _context.Set<T>();
        }

        public Task Create<T>(T entity) where T : class
        {
            throw new System.NotImplementedException();
        }

        public Task Delete<T>(int id) where T : class
        {
            throw new System.NotImplementedException();
        }

        public Task Update<T>(int id, T entity) where T : class
        {
            throw new System.NotImplementedException();
        }

        public void Dispose()
        {
            _context?.Dispose();
        }
    }
}

IRepository.cs

using System;
using System.Linq;
using System.Threading.Tasks;

namespace churchy.Repository
{
    public interface IRepository : IDisposable
    {
        IQueryable<T> GetAll<T>() where T : class;
        Task Create<T>(T entity) where T :class;
        Task Update<T>(int id, T entity) where T : class;
        Task Delete<T>(int id) where T : class;
    }
}

ChurchController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using churchy.Service.Abstractions;

namespace churchy.Controllers
{
    [Route("api/church")]
    public class ChurchController : Controller
    {
        private readonly IChurchService _churchService;
        public ChurchController(IChurchService churchService)
        {
            _churchService = churchService;
        }
        // GET: api/<controller>
        [HttpGet]
        public IActionResult GetAllAsync()
        {
            var response = _churchService.getChurches();

            return Ok(response);
        }

        // GET api/<controller>/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value3";
        }

        // POST api/<controller>
        [HttpPost]
        public void Post([FromBody]string value)
        {
        }

        // PUT api/<controller>/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/<controller>/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}

【问题讨论】:

  • 调试时,ChurchContext 类中调用了哪个构造函数?
  • 如果您希望 IRepository 将由依赖注入容器自动实例化,请将上下文作为参数添加到存储库的构造函数。 public Repository(ChurchContext context)
  • 你的控制器依赖于IChurchService,但你没有展示它的实现。如果服务依赖于存储库,则应将其作为构造函数参数引入。

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


【解决方案1】:

这是你最基本的问题:

public Repository()
{
    _context = new ChurchContext();
}

这与依赖注入相反。您手动创建的上下文配置。

快速回答:

public Repository(ChurchContext context)
{
    _context = context;
}

此外:

【讨论】:

  • 感谢您的回复,我确实更改了添加 D Ppublic Repository() { _context = new ChurchContext(); }
  • 进行了更改,但现在出现此错误 There is no argument given that corresponds to the required formal parameter 'context' of 'Repository.Repository(ChurchContext)' x ` namespace Churchy.Repository { public class RepositoryFactory : IRepositoryFactory { public IRepository CreateRepository() { return new Repository(); } } }`
  • @user2286483 那个类不应该存在,DI Container 会为你创建实例,你不需要它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-02
  • 2019-02-17
  • 2021-05-04
  • 2016-11-15
  • 2018-11-12
  • 2018-12-15
  • 2020-06-16
相关资源
最近更新 更多