1

I recently reverse engineered a table to create a model and a context class. I then created a controller and a view from VS 2017 scaffolding. When I try to load my page I receive the following error:

InvalidOperationException: Unable to resolve service for type 'TestSolutions.Models.TraderRoute.TraderContext' while attempting to activate 'TestSolutions.Controllers.RoutePartnersController'.

Microsoft.Extensions.Internal.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)

Controller.

public class RoutePartnersController : Controller
{
    private readonly TraderContext _context;

    public RoutePartnersController(TraderContext context)
    {
        _context = context;    
    }

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

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

        var routePartner = await _context.RoutePartner
            .SingleOrDefaultAsync(m => m.PartnerId == id);
        if (routePartner == null)
        {
            return NotFound();
        }

        return View(routePartner);
    }

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

    // POST: RoutePartners/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,PartnerId,RouteCompany,RouteCode,Dark,Lit,Contra,CreateDate,CreateBy")] RoutePartner routePartner)
    {
        if (ModelState.IsValid)
        {
            routePartner.PartnerId = Guid.NewGuid();
            _context.Add(routePartner);
            await _context.SaveChangesAsync();
            return RedirectToAction("Index");
        }
        return View(routePartner);
    }

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

        var routePartner = await _context.RoutePartner.SingleOrDefaultAsync(m => m.PartnerId == id);
        if (routePartner == null)
        {
            return NotFound();
        }
        return View(routePartner);
    }

    // POST: RoutePartners/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(Guid id, [Bind("Id,PartnerId,RouteCompany,RouteCode,Dark,Lit,Contra,CreateDate,CreateBy")] RoutePartner routePartner)
    {
        if (id != routePartner.PartnerId)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            try
            {
                _context.Update(routePartner);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!RoutePartnerExists(routePartner.PartnerId))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToAction("Index");
        }
        return View(routePartner);
    }

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

        var routePartner = await _context.RoutePartner
            .SingleOrDefaultAsync(m => m.PartnerId == id);
        if (routePartner == null)
        {
            return NotFound();
        }

        return View(routePartner);
    }

    // POST: RoutePartners/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> DeleteConfirmed(Guid id)
    {
        var routePartner = await _context.RoutePartner.SingleOrDefaultAsync(m => m.PartnerId == id);
        _context.RoutePartner.Remove(routePartner);
        await _context.SaveChangesAsync();
        return RedirectToAction("Index");
    }

    private bool RoutePartnerExists(Guid id)
    {
        return _context.RoutePartner.Any(e => e.PartnerId == id);
    }
}

Here's my view:

@model TestSolutions.Models.TraderRoute.RoutePartner
@{ViewData["Title"] = "Details";}


<h2>Details</h2>

<div>
<h4>RoutePartner</h4>
<hr />

<dl class="dl-horizontal">
<dt>
        @Html.DisplayNameFor(model => model.Id)
</dt>
<dd>
        @Html.DisplayFor(model => model.Id)
</dd>
<dt>
        @Html.DisplayNameFor(model => model.Dark)
</dt>
<dd>
        @Html.DisplayFor(model => model.Dark)
</dd>
<dt>
        @Html.DisplayNameFor(model => model.Lit)
</dt>
<dd>
        @Html.DisplayFor(model => model.Lit)
    </dd>
    <dt>
        @Html.DisplayNameFor(model => model.Contra)
    </dt>
    <dd>
        @Html.DisplayFor(model => model.Contra)
    </dd>
    <dt>
        @Html.DisplayNameFor(model => model.CreateDate)
    </dt>
    <dd>
        @Html.DisplayFor(model => model.CreateDate)
    </dd>
    <dt>
        @Html.DisplayNameFor(model => model.CreateBy)
    </dt>
    <dd>
        @Html.DisplayFor(model => model.CreateBy)
    </dd>
</dl>
</div>
<div>
    @Html.ActionLink("Edit", "Edit", new { /* id = Model.PrimaryKey */ }) | <a asp-action="Index">Back to List</a>
</div>
3
  • 1
    Could you please share the controller and view? Commented Jul 5, 2017 at 18:54
  • Just added, thank you Commented Jul 5, 2017 at 20:36
  • Could you also show how you register TraderContext with DI in your Startup class? Commented Jul 5, 2017 at 21:57

1 Answer 1

2

It seems that TraderContext is not registered in DI (IoC) container. Please make sure you register them.

public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        ...

        services.AddDbContext<TraderContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
                // Remove this if you use SQL 2012 or higher.
                b => b.UseRowNumberForPaging()));
        ...
    }
}    

I normally use the following scaffold scripts to generate entities from existing tables -

Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Tools
Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design

Scaffold-DbContext "Server=SERVER;Database=DATABASE;Trusted_Connection=True;MultipleActiveResultSets=true" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
Sign up to request clarification or add additional context in comments.

3 Comments

You were right!!!!! Thank you so much, I had overlooked the registration process. Now the page is loaded correctly. However, when I click the Edit link, I receive a "page not found error". The Edit link is what's built from the scaffolding. Any idea what I'm doing wrong here?
Could you please create a new question for Edit link issue? I'm glad to help you. If this answer solves the original question, please mark it as Answer.
Absolutely. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.