with tutorial net mvc migrations framework enable data asp c# entity-framework asp.net-core-mvc entity-framework-core seeding

c# - tutorial - Datos iniciales de semilla en Entity Framework 7 RC 1 y ASP.NET MVC 6



migration asp core (5)

Desde la introducción de EF / MVC , solo:

  1. dependencia-inyecta tu DbContext ( SchoolContext abajo) directamente en Startup.Configure() *
  2. pase su DbContext a una función ( DbInitializer.Initialize continuación) que hace algo como:
    1. asegúrese de que la base de datos se crea o que se migra context.Database.EnsureCreated(); considere context.Database.Migrate();
    2. devuelve si ya está sembrado if (context.Students.Any()) { return; } if (context.Students.Any()) { return; }
    3. else seed context.Students.Add({...}); context.SaveChanges(); context.Students.Add({...}); context.SaveChanges();

Como aquí:

public void Configure(..., ..., SchoolContext context) { ... DbInitializer.Initialize(context); }

...

public static class DbInitializer { public static void Initialize(SchoolContext context) { context.Database.EnsureCreated(); // Look for any students. if (context.Students.Any()) { return; // DB has been seeded } var students = new Student[] { new Student{FirstMidName="Carson",LastName="Alexander",EnrollmentDate=DateTime.Parse("2005-09-01")}, ... }; foreach (Student s in students) { context.Students.Add(s); } context.SaveChanges(); ...

* La inyección de dependencia en Startup.Configure() es la razón por la que mi respuesta es válida (aunque ya se acepta otra respuesta).

  1. La inyección de dependencias de DbContext en Startup.Configure() se realiza en EF / MVC Intro
  2. No hay otra respuesta aquí, solo la dependencia se inyecta en Configurar; ya sea GetService() y / o GetRequiredService() , o crear una instancia de un nuevo DbContext . Puede que no necesites tanto código. Por otra parte, es posible que necesite mucho código (es decir, si se eliminó el DbContext de Dependency-Injected, que es donde GetService() es necesario para crear un nuevo Ámbito. .

Esta pregunta ya tiene una respuesta aquí:

Parece que en Entity Framework 7 todavía no hay soporte nativo para datos semilla ( https://github.com/aspnet/EntityFramework/issues/629 ).

No hay DbMigrationsConfiguration clase DbMigrationsConfiguration , ningún método Seed en el código de plantilla proporcionado por Microsoft.

Entonces, ¿cómo generar datos en la aplicación web ASP.NET MVC 6 que utiliza Entity Framework 7 RC 1?


He creado el método Seed() privado en mi Startup.cs pero también me gusta su enfoque, ya que se puede usar no solo durante el inicio de la aplicación.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { this.Seed(); } private void Seed() { using (var db = new MyDbContext()) { db.Database.Migrate(); // Seed code db.SaveChanges(); } }


He encontrado una solución temporal para mí.

Podemos crear un método SeedData que amplía el IApplicationBuilder luego obtiene una instancia de nuestra clase de contexto de base de datos a través del método GetService y lo utiliza para inicializar los datos.

Aquí es cómo se ve mi método de extensión:

using Microsoft.AspNet.Builder; using Microsoft.Extensions.DependencyInjection; public static class DataSeeder { // TODO: Move this code when seed data is implemented in EF 7 /// <summary> /// This is a workaround for missing seed data functionality in EF 7.0-rc1 /// More info: https://github.com/aspnet/EntityFramework/issues/629 /// </summary> /// <param name="app"> /// An instance that provides the mechanisms to get instance of the database context. /// </param> public static void SeedData(this IApplicationBuilder app) { var db = app.ApplicationServices.GetService<ApplicationDbContext>(); // TODO: Add seed logic here db.SaveChanges(); } }

Para usarlo ponga app.SeedData(); Línea en el método de Configure de la clase de Startup de la aplicación (ubicada en el proyecto web en el archivo llamado Startup.cs ).

// This method gets called by the runtime. // Use this method to configure the HTTP request pipeline. public void Configure( IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.SeedData(); // Other configuration code }


Para EF Core RTM 1.0 y ASP.NET Core RTM 1.0

Primero crea el método semilla. Aquí porque estamos fuera del alcance de la solicitud actual, debemos crearla de forma manual:

using System.Collections.Generic; using System.Linq; using Core1RtmEmptyTest.Entities; using Microsoft.Extensions.DependencyInjection; namespace Core1RtmEmptyTest.Migrations { public static class ApplicationDbContextSeedData { public static void SeedData(this IServiceScopeFactory scopeFactory) { using (var serviceScope = scopeFactory.CreateScope()) { var context = serviceScope.ServiceProvider.GetService<ApplicationDbContext>(); if (!context.Persons.Any()) { var persons = new List<Person> { new Person { FirstName = "Admin", LastName = "User" } }; context.AddRange(persons); context.SaveChanges(); } } } } }

Luego especifique el tiempo de vida correcto de ApplicationDbContext

public void ConfigureServices(IServiceCollection services) { services.AddDbContext<ApplicationDbContext>(ServiceLifetime.Scoped);

Y finalmente llame al método SeedData() desde el método Configure

public void Configure(IServiceScopeFactory scopeFactory) { scopeFactory.SeedData();


Puede crear el método de semilla estática dentro de ApplicationDbContext y pasar IApplicationBuilder como parámetro. Entonces llama a este método en el Startup.cs .

public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } public static void Seed(IApplicationBuilder applicationBuilder) { using (var context=applicationBuilder.ApplicationServices.GetRequiredService<ApplicationDbContext>()) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); for(int i = 1; i< 1000; i++) { context.Movies.Add(new Movie { Genre = "Action", ReleaseDate =DateTime.Today, Title = "Movie "+i }); } context.SaveChanges(); } } public DbSet<Movie> Movies { get; set; } }

En el método Configure() dentro de Startup.cs , llame a ApplicationDbContext.Seed(app)

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseIdentity(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); ApplicationDbContext.Seed(app); }