tutorial onmodelcreating net mvc framework first español con code asp c# asp.net .net entity-framework asp.net-core

c# - onmodelcreating - No se puede resolver DbContext en ASP.NET Core 2.0



mvc entity framework español (3)

En primer lugar, estoy tratando de sembrar mi base de datos con datos de muestra. He leído que esta es la forma de hacerlo (en Startup.Configure ) (consulte la base de datos de ASP.NET Core RC2 )

Estoy usando ASP.NET Core 2.0 con las opciones predeterminadas.

Como de costumbre, registro mi DbContext en ConfigureServices . Pero después de eso, en el método Startup.Configure, cuando trato de resolverlo usando GetRequiredService , GetRequiredService con este mensaje:

System.InvalidOperationException: ''No se puede resolver el servicio con ámbito'' SGDTP.Infrastructure.Context.SGDTPContext ''desde el proveedor raíz.''

Mi clase de inicio como esta:

public abstract class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddDbContext<SGDTPContext>(options => options.UseInMemoryDatabase("MyDatabase")) services.AddMvc(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(); SeedDatabase(app); } private static void SeedDatabase(IApplicationBuilder app) { using (var context = app.ApplicationServices.GetRequiredService<SGDTPContext>()) { // Seed the Database //... } } }

¿Qué estoy haciendo mal? Además, ¿es este el mejor lugar para crear datos semilla?


Está registrando SGDTPContext como un servicio con ámbito y luego intenta acceder a él fuera de un ámbito. Para crear un ámbito para sus propósitos, puede utilizar la siguiente solución:

using (var serviceScope = app.ApplicationServices.CreateScope()) { var context = serviceScope.ServiceProvider.GetService<SGDTPContext>(); // Seed the database. }

Aquí hay un viejo issue Github que discute este enfoque.

Gracias a @khellang por señalar el método de extensión CreateScope en su comentario.

Vea el comentario y la answer @ Tseng para obtener una explicación sobre la mejor manera de abordar los datos de siembra en EF Core 2.


Recibía este error mientras seguía el tutorial oficial de ASP.Net MVC Core, en la sección en la que se supone que debe agregar datos sembrados a su aplicación. Larga historia corta, sumando estas dos líneas.

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

a la clase SeedData me lo resolvió:

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 } ...

No puedo decirle POR QUÉ, pero estas fueron dos de las opciones que obtuve al seguir la opción de corrección rápida Alt + Enter .


public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var key = Encoding.ASCII.GetBytes(Configuration.GetSection("AppSettings:Token").Value); services.AddDbContext<DataContext>(x => x.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")).EnableSensitiveDataLogging()); services.AddMvc(); services.AddTransient<Seed>(); services.AddCors(); services.AddScoped<IAuthRepository, AuthRepository>(); services.AddScoped<IUserRepository, UserRepository>(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(Options => { Options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false }; } ); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env ,Seed seeder) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler(builder => { builder.Run(async context => { context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.Response.Headers.Add("Access-Control-Allow-Origin", "*"); var error = context.Features.Get<IExceptionHandlerFeature>(); if (error != null) { context.Response.AddApplicationError(error.Error.Message); await context.Response.WriteAsync(error.Error.Message).ConfigureAwait(false); } }); }); } seeder.SeedUser(); app.UseCors(x=>x.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials()); app.UseMvc(); } }

}