1

I am working on Boilerplate.web.app template to create basic CRUD application.

I am using DB first approach. So, first I created the database, then cloned https://github.com/ParvezMirani/Boilerplate.Web.App in Visual Studio 2017, installed npm packages.

Linked the database by running the custom command in npm console:

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

It has successfully imported the model classes from db using above command. (Entity framework was not compatible with the template so used this step instead).

I added a new controller "customers" to implement CRUD.

Now when I run the project in browser, I am able to see the index page of homeController in boilerplate template but not of the custom customersController that comes from the table in database that I made.

I get the following error when I try to open customers page in url:

InvalidOperationException: Unable to resolve service for type 'Boilerplate.Web.App.Models.DevOnBoardTaskContext' while attempting to activate 'Boilerplate.Web.App.Controllers.CustomersController'.

There is a warning shown in context class in models as: #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.

    `// *****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

Could someone please help me resolve it. Many Thanks!

Sahil Sharma
  • 1,813
  • 1
  • 16
  • 37
Ribu
  • 101
  • 3
  • 8

0 Answers0