InvalidOperationException:尝试激活〜时无法解析类型为'Boilerplate.Web.App.Models.DevOnBoardTaskContext'的服务

时间:2019-01-23 22:04:48

标签: c# sql asp.net-mvc react-boilerplate

我正在使用Boilerplate.web.app模板来创建基本的CRUD应用程序。

我正在使用数据库优先方法。因此,首先我创建了数据库,然后在Visual Studio 2017中克隆了https://github.com/ParvezMirani/Boilerplate.Web.App,安装了npm软件包。

通过在npm控制台中运行定制命令来链接数据库:

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

它已使用上述命令成功地从db导入了模型类。 (实体框架与模板不兼容,因此请在此步骤中使用)。

我添加了一个新的控制器“客户”以实现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);
        }
    }
}

enter image description here

有人可以帮助我解决它吗?非常感谢!

0 个答案:

没有答案