У меня есть приложение ASP.NET 5 с API и отдельная библиотека классов с Entity Framework 7.
Я столкнулся с некоторыми проблемами, пытаясь заставить работать заполнение и автоматические миграции. У меня есть класс DbInitializer в библиотеке классов EntityFramework, который вызывается классом запуска в проекте API.
Класс запуска в проекте API:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Data.Entity;
using MyApp.Data.EntityFramework.DataContext;
using MyApp.Data.EntityFramework;
namespace MyApp.API
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json");
if (env.IsEnvironment("Development"))
{
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}
builder.AddEnvironmentVariables();
Configuration = builder.Build().ReloadOnChanged("appsettings.json");
}
public IConfigurationRoot Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<MyAppDataContext>(options =>
options.UseSqlServer(Configuration["Data:MyAppConnection:ConnectionString"]));
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
// 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)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseIISPlatformHandler();
app.UseApplicationInsightsRequestTelemetry();
app.UseApplicationInsightsExceptionTelemetry();
app.UseStaticFiles();
app.UseMvc();
DbInitializer.Initialize(app.ApplicationServices);
}
// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}
}
Класс DbInitializer в библиотеке классов Entity Framework:
using MyApp.Data.EntityFramework.DataContext;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Data.Entity;
using MyApp.Domain.Model.Leaflets;
namespace MyApp.Data.EntityFramework
{
public static class DbInitializer
{
private static MyAppDataContext context;
public static void Initialize(IServiceProvider serviceProvider)
{
context = (MyAppDataContext)serviceProvider.GetService<MyAppDataContext>();
context.Database.Migrate();
InitializeLeaflets();
}
private static void InitializeLeaflets()
{
if (!context.Leaflets.Any())
{
var leaflets = new List<Leaflet>
{
new Leaflet { Title="Leaflet 1" },
new Leaflet { Title="Leaflet 2" },
new Leaflet { Title="Leaflet 3" },
new Leaflet { Title="Leaflet 4" },
};
context.Leaflets.AddRange(leaflets);
context.SaveChanges();
}
}
}
}
После этого сообщения (EntityFramework 7 (EF7) Migrations . DbContext и StartUp Project находятся в разных сборках) Я запускаю заполнение и обновление базы данных с помощью следующих команд:
cd MyApp.API
dnx ef migrations add Initial -p MyApp.Data.EntityFramework
dnx ef database update -p MyApp.Data.EntityFramework
Это создает базу данных и необходимые таблицы, но не выполняет заполнение (и мне все еще нужна миграция, просто запуск обновления базы данных не работает.)
Есть ли способ настроить заполнение и автоматические миграции?