InvalidOperationException: невозможно разрешить службу для типа 'Boilerplate.Web.App.Models.DevOnBoardTaskContext' при попытке активировать ~ - PullRequest
0 голосов
/ 24 января 2019

Я работаю над шаблоном Boilerplate.web.app для создания базового приложения CRUD.

Я использую БД первый подход. Итак, сначала я создал базу данных, затем клонировал https://github.com/ParvezMirani/Boilerplate.Web.App в Visual Studio 2017, установил пакеты npm.

Связал базу данных, выполнив пользовательскую команду в консоли npm:

Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

Он успешно импортировал классы моделей из БД, используя приведенную выше команду. (Entity Framework не был совместим с шаблоном, поэтому вместо этого использовал этот шаг).

Я добавил новый контроллер «клиенты» для реализации CRUD.

Теперь, когда я запускаю проект в браузере, я могу видеть индексную страницу homeController в шаблонном шаблоне, но не пользовательский customerController, полученный из таблицы в базе данных, которую я создал.

При попытке открыть страницу клиентов в URL я получаю следующую ошибку:

InvalidOperationException: невозможно разрешить службу для типа 'Boilerplate.Web.App.Models.DevOnBoardTaskContext' при попытке активировать 'Boilerplate.Web.App.Controllers.CustomersController'.

В контекстном классе в моделях отображается предупреждение: #warning Чтобы защитить потенциально конфиденциальную информацию в строке подключения, вы должны удалить ее из исходного кода. См. http://go.microsoft.com/fwlink/?LinkId=723263 для получения инструкций по хранению строк подключения.

    `// *****DevOnBoardTaskContext.cs******`
        using System;
        using Microsoft.EntityFrameworkCore;
        using Microsoft.EntityFrameworkCore.Metadata;

        namespace Boilerplate.Web.App.Models
        {
            public partial

 class DevOnBoardTaskContext : DbContext
        {
            public DevOnBoardTaskContext()
            {
            }

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

            public virtual DbSet<Customer> Customer { get; set; }
            public virtual DbSet<Product> Product { get; set; }
            public virtual DbSet<Sales> Sales { get; set; }
            public virtual DbSet<Store> Store { get; set; }

            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                if (!optionsBuilder.IsConfigured)
                {
    #warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
                    optionsBuilder.UseSqlServer("Server=RIBU\\SQLEXPRESS;Database=DevOnBoardTask;Trusted_Connection=True;");
                }
            }

            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                modelBuilder.Entity<Customer>(entity =>
                {
                    entity.Property(e => e.Address)
                        .IsRequired()
                        .HasMaxLength(50);

                    entity.Property(e => e.Name)
                        .IsRequired()
                        .HasMaxLength(50);
                });

                modelBuilder.Entity<Product>(entity =>
                {
                    entity.Property(e => e.Name)
                        .IsRequired()
                        .HasMaxLength(50);
                });

                modelBuilder.Entity<Sales>(entity =>
                {
                    entity.Property(e => e.DateSold).HasColumnType("date");

                    entity.HasOne(d => d.Customer)
                        .WithMany(p => p.Sales)
                        .HasForeignKey(d => d.CustomerId)
                        .OnDelete(DeleteBehavior.ClientSetNull)
                        .HasConstraintName("FK_Sales_Customer");

                    entity.HasOne(d => d.Product)
                        .WithMany(p => p.Sales)
                        .HasForeignKey(d => d.ProductId)
                        .OnDelete(DeleteBehavior.ClientSetNull)
                        .HasConstraintName("FK_Sales_Product");

                    entity.HasOne(d => d.Store)
                        .WithMany(p => p.Sales)
                        .HasForeignKey(d => d.StoreId)
                        .OnDelete(DeleteBehavior.ClientSetNull)
                        .HasConstraintName("FK_Sales_Store");
                });

                modelBuilder.Entity<Store>(entity =>
                {
                    entity.Property(e => e.Address)
                        .IsRequired()
                        .HasMaxLength(50);

                    entity.Property(e => e.Name)
                        .IsRequired()
                        .HasMaxLength(50);
                });
            }
        }
    }

CustomersController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Boilerplate.Web.App.Models;

namespace Boilerplate.Web.App.Controllers
{
    public class CustomersController : Controller
    {
        private readonly DevOnBoardTaskContext _context;

        public CustomersController(DevOnBoardTaskContext context)
        {
            _context = context;
        }

        // GET: Customers
        public async Task<IActionResult> Index()
        {
            return View(await _context.Customer.ToListAsync());
        }

        // GET: Customers/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var customer = await _context.Customer
                .FirstOrDefaultAsync(m => m.Id == id);
            if (customer == null)
            {
                return NotFound();
            }

            return View(customer);
        }

        // GET: Customers/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: Customers/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Id,Name,Address")] Customer customer)
        {
            if (ModelState.IsValid)
            {
                _context.Add(customer);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(customer);
        }

        // GET: Customers/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var customer = await _context.Customer.FindAsync(id);
            if (customer == null)
            {
                return NotFound();
            }
            return View(customer);
        }

        // POST: Customers/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("Id,Name,Address")] Customer customer)
        {
            if (id != customer.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(customer);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!CustomerExists(customer.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(customer);
        }

        // GET: Customers/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var customer = await _context.Customer
                .FirstOrDefaultAsync(m => m.Id == id);
            if (customer == null)
            {
                return NotFound();
            }

            return View(customer);
        }

        // POST: Customers/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var customer = await _context.Customer.FindAsync(id);
            _context.Customer.Remove(customer);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool CustomerExists(int id)
        {
            return _context.Customer.Any(e => e.Id == id);
        }
    }
}

введите описание изображения здесь

Может кто-нибудь, пожалуйста, помогите мне решить это. Большое спасибо!

...