简体   繁体   中英

EF CodeFirst Seed method do not make any changes in database

I'm trying to insert some default values in database via method Seed. All code look completely correct as far as I can see. But after running update-database command there is no new records as expected. Probably I'm missing some details. Could you please advise how can I fix this?

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();
            }
        }
    }

Related to this article http://entityframework.codeplex.com/workitem/1689 , it's not possible to use migration AND "DropCreateDatabaseAlways" as the initializer at the same time.

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>());
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM