.NET Core MVC控制器错误

时间:2017-07-05 18:46:09

标签: asp.net-mvc asp.net-core invalidoperationexception

我最近反向设计了一个表来创建模型和上下文类。然后我创建了VS 2017脚手架的控制器和视图。当我尝试加载页面时,收到以下错误:

  

InvalidOperationException:无法解析类型的服务   ' TestSolutions.Models.TraderRoute.TraderContext'在尝试时   激活' TestSolutions.Controllers.RoutePartnersController'。

     

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

控制器。

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

以下是我的观点:

@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>

1 个答案:

答案 0 :(得分:1)

似乎TraderContext未在DI(IoC)容器中注册。请确保您注册。

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()));
        ...
    }
}    

我通常使用以下脚手架脚本从现有表格生成实体 -

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