简体   繁体   English

EF CodeFirst Seed方法不会在数据库中进行任何更改

[英]EF CodeFirst Seed method do not make any changes in database

I'm trying to insert some default values in database via method Seed. 我试图通过方法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. 但是在运行update-database命令之后,没有新记录如预期的那样。 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. 与本文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. 由RoMiller EF Team Triage在2013年9月28日上午4:56关闭:这是“通过设计”,这是我们在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). 如果使用该初始化程序创建数据库,则将单个条目添加到__MigrationsHistory表中,该表随后使数据库无法用于迁移(因为这些初始化程序不使用您的迁移来创建数据库)。 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. 如果只希望应用迁移,则可以使用MigrateDatabaseToLatestVersion初始化程序。 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(). 如果要删除数据库,则可以轻松地将其包装在自定义初始化程序中,该初始化程序包括对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>());
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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