EF Code First Seed 方法不对数据库进行任何更改

EF CodeFirst Seed method do not make any changes in database

我正在尝试通过 Seed 方法在数据库中插入一些默认值。据我所知,所有代码看起来都完全正确。但是在 运行 update-database 命令之后没有预期的新记录。可能我遗漏了一些细节。你能告诉我如何解决这个问题吗?

public class JwtContext : DbContext
    {

        public JwtContext() : base("name=Jwt")
        {
            Database.SetInitializer(new JwtDbInitializer<JwtContext>());
        }

        public virtual DbSet<Audience> Audience { get; set; }
        public virtual DbSet<Roles> Roles { get; set; }
        public virtual DbSet<Users> Users { get; set; }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Roles>()
                .HasMany(e => e.Users)
                .WithRequired(e => e.Roles)
                .HasForeignKey(e => e.RoleId)
                .WillCascadeOnDelete(true);

            modelBuilder.Entity<Audience>()
                .HasMany(e => e.Users)
                .WithRequired(e => e.Audiences)
                .HasForeignKey(e => e.AudienceId)
                .WillCascadeOnDelete(true);
        }
        private class JwtDbInitializer<T> : DropCreateDatabaseAlways<JwtContext>
        {
            protected override void Seed(JwtContext context)
            {
                base.Seed(context);
                var audience = new Audience
                {
                    ClientId = "some_client_id",
                    Base64Secret = "some_secret",
                    Name = "Agromash.Api"
                };
                context.Audience.Add(audience);
                context.SaveChanges();
                IList<Roles> defaultRole = new List<Roles>();
                defaultRole.Add(new Roles { Name = "Admin" });
                defaultRole.Add(new Roles { Name = "Moder" });
                defaultRole.Add(new Roles { Name = "User" });
                foreach (var role in defaultRole)
                {
                    context.Roles.Add(role);
                }
                context.SaveChanges();
                var user = new Users { Email = "email", IsActive = true, Password = "password", RoleId = 1, AudienceId = 1 };
                //SiteGlobal.Email, Password = SiteGlobal.Password
                context.Users.Add(user);
                context.SaveChanges();
            }
        }
    }

与本文 http://entityframework.codeplex.com/workitem/1689 相关,无法同时使用迁移和 "DropCreateDatabaseAlways" 作为初始值设定项。

Closed Sep 28, 2013 at 4:56 AM by RoMiller EF Team Triage: This is 'By Design' and was an intentional change we took in EF6. If this initializer is used to create the database then a single entry is added to the __MigrationsHistory table which then renders the database un-usable with migrations (since these initializers don't use your migrations to create the database). This has confused a large number of people in previous releases, so we opted to not automatically create database/schema when migrations is enabled.

You can use the MigrateDatabaseToLatestVersion initializer if you just want your migrations to be applied. If you want to drop the database then you could easily wrap this in a custom initializer that includes a call to context.Database.Delete().

public JwtContext() : base("name=Jwt")
    {
        // to alter the database.This tell the database to close all connection and if a transaction is open to rollback this one.
         Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction
            , string.Format("ALTER DATABASE {0} SET SINGLE_USER WITH ROLLBACK IMMEDIATE", Database.Connection.Database));

        Database.Delete();
        Database.SetInitializer(new JwtDbInitializer<JwtContext>());
    }