InvalidOperationException: для этого DbContext не настроен поставщик базы данных. - PullRequest
0 голосов
/ 26 мая 2018

создание веб-API с использованием entityframeworkcore 2.03 .net core

продолжайте получать следующую ошибку, пытаясь решить все возможные проблемы, не зная, в чем проблема, если кто-то еще имел эту ошибку?

InvalidOperationException: для этого DbContext не настроен поставщик базы данных.Поставщик может быть настроен путем переопределения метода DbContext.OnConfiguring или с помощью AddDbContext в поставщике службы приложений.Если используется AddDbContext, то также убедитесь, что ваш тип DbContext принимает объект DbContextOptions в своем конструкторе и передает его базовому конструктору для DbContext

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)
        {
        }
    }
}

1 Ответ

0 голосов
/ 26 мая 2018

Вот ваша самая фундаментальная проблема:

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

Это противоположность инъекции зависимости.Для этого контекста, который вы создаете вручную, настроено , а не * 1005. *.

Быстрый ответ:

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

Более того:

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...