在Web API应用程序中运行Entity Framework 6.1。我有我的DatabaseContext设置,当我从包管理器控制台运行Update-Database时,数据库会正确创建和播种。
但是,如果我删除或手动创建数据库然后运行应用程序,实体框架将在数据库中创建表,但不会运行填充数据的种子方法。任何人都知道为什么种子数据不会运行?代码如下。
namespace MyProject.API.DBMigrations
{
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using MyProject.API.Infrastructure;
using MyProject.Models.Business_Models;
using MyProject.Models.Domain_Models;
using MyProject.Models.Models;
internal sealed class DatabaseConfiguration : DbMigrationsConfiguration<MyProject.API.Infrastructure.ApplicationDbContext>
{
public DatabaseConfiguration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
MigrationsDirectory = @"DBMigrations";
}
protected override void Seed(MyProject.API.Infrastructure.ApplicationDbContext context)
{
// This method will be called after migrating to the latest version.
DatabaseSeeder.SeedSecurity(context);
DatabaseSeeder.SeedBusiness(context);
base.Seed(context);
}
}
public class MyProjectDBInitializer : DropCreateDatabaseIfModelChanges<MyProject.API.Infrastructure.ApplicationDbContext>
{
// This Seed method is run when database is initialized if it is created if none exists
protected override void Seed(MyProject.API.Infrastructure.ApplicationDbContext context)
{
DatabaseSeeder.SeedBusiness(context);
DatabaseSeeder.SeedSecurity(context);
base.Seed(context);
}
}
public static class DatabaseSeeder
{
public static void SeedSecurity(MyProject.API.Infrastructure.ApplicationDbContext context)
{
//SEED Data added here (redacted for brevity)
}
public static void SeedBusiness(MyProject.API.Infrastructure.ApplicationDbContext context)
{
//SEED Data added here (redacted for brevity)
}
}
}
以下是我设置初始化程序的数据库上下文的一部分。我甚至尝试在global.asax中设置初始化程序,但这没有用。
namespace MyProject.API.Infrastructure
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
Configuration.LazyLoadingEnabled = true;
System.Data.Entity.Database.SetInitializer<ApplicationDbContext>(new MyProjectDBInitializer());
}
// no change: this static ctor called the first time this type is referenced
static ApplicationDbContext() {
System.Data.Entity.Database.SetInitializer<ApplicationDbContext>(new MyProjectDBInitializer());
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Fluent api code here
// Add foreign key constraint here or else nullable doesn't work when EF does savechanges
modelBuilder.Entity<GiftCardTransaction>().Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
base.OnModelCreating(modelBuilder);
}
}
}