Cannot resolve DbContext in ASP.NET Core 2.0

.net asp.net asp.net-core c# entity-framework

Accepted Answer

You are signing up.SGDTPContext as a outside service and then making an effort to access it. To build a scope inside yourSeedDatabase use the following approach:

using (var serviceScope = app.ApplicationServices.CreateScope())
{
    var context = serviceScope.ServiceProvider.GetService<SGDTPContext>();

    // Seed the database.
}

A special thanks to @khellang for bringing up theCreateScope How to implement seeding in EF Core 2 is discussed in the comments, along with an extension technique to @Tseng's remark and answer.

69
9/8/2019 9:51:07 PM

Popular Answer

When attempting to add seeded data to my application as instructed in the official ASP.Net MVC Core tutorial, I encountered this problem. To cut to the chase, add these two lines.

 using Microsoft.EntityFrameworkCore;
 using Microsoft.Extensions.DependencyInjection;

to theSeedData My class provided the solution:

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;

namespace MvcMovie.Models
{
public static class SeedData
{
    public static void Initialize(IServiceProvider serviceProvider)
    {
        using (var context = new MvcMovieContext(

           serviceProvider.GetRequiredService<DbContextOptions<MvcMovieContext>>()))
        {
            // Look for any movies.
            if (context.Movie.Any())
            {
                return;   // DB has been seeded
            }
  ...

I'm not sure why, but these are two of the ideas I came up with after examining theAlt + Enter rapid-fix alternative



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow