Friday, January 9, 2015

EF: Database initialization strategy Code First -(1)

 
1. 
public class AppDBContext : DbContext
    {
        public AppDBContext() : base("mycon")
        {
           //  Database.SetInitializer<AppDBContext>(new AppDBInitializer());
           //  if (!WebSecurity.Initialized)
           //  {
           //    //Database.SetInitializer<AppDBContext>(new AppDBInitializer());
           //    WebSecurity.InitializeDatabaseConnection("mycon", "UserProfile", "UserId", 
                                                        "UserName", autoCreateTables: true);
           //  }
        }
        public DbSet<User> User { getset; }
        public DbSet<Category> Category { getset; }
        public DbSet<BlogPost> BlogPost { getset; }
        public DbSet<Comment> Comment { getset; }
 
        public DbSet<UserProfile> UserProfile { getset; }
 
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new UserConfiguration());
            modelBuilder.Configurations.Add(new CategoryConfiguration());
            modelBuilder.Configurations.Add(new BlogConfiguration());
            modelBuilder.Configurations.Add(new CommentConfiguration());            
            base.OnModelCreating(modelBuilder);
        }
    }
 
 
 2....................................
  public class AppDBInitializer : DropCreateDatabaseAlways<AppDBContext>
    {
        private static void InitializeWebSecurity()
        {
          WebSecurity.InitializeDatabaseConnection("mycon","UserProfile""UserId"
                                                          "UserName", autoCreateTables: true);
            
            var roles = (SimpleRoleProvider)Roles.Provider;
            var membership = (SimpleMembershipProvider)Membership.Provider;
 
            if (!roles.RoleExists("Admin"))
            {
                roles.CreateRole("Admin");
            }
            if (membership.GetUser("test"false) == null)
            {
                membership.CreateUserAndAccount("test""test");
            }
            if (!roles.GetRolesForUser("test").Contains("Admin"))
            {
                roles.AddUsersToRoles(new[] { "test" }, new[] { "admin" });
            } 
        }      
 
        protected override void Seed(AppDBContext context)
        {
            InitializeWebSecurity();
 
            IList<Category> category = new List<Category>();
            category.Add(new Category { CategoryName="Action"});
            category.Add(new Category { CategoryName = "Thrill" });
            foreach (Category item in category)
            {
                context.Category.Add(item);
            }
          base.Seed(context);
        }
    } 
 
 
 3...................................
    protected void Application_Start()
        {
   // http://stackoverflow.com/questions/16542347/database-initialization-strategy-code-first
            AreaRegistration.RegisterAllAreas();
 
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
 
 
            Database.SetInitializer<AppDBContext>(new AppDBInitializer());
            AppDBContext context = new AppDBContext();
            context.Database.Initialize(true);
            if (!WebSecurity.Initialized)
                WebSecurity.InitializeDatabaseConnection("mycon",
                    "UserProfile""UserId""UserName", autoCreateTables: true);
        } 
 
 
 public class BlogConfiguration : EntityTypeConfiguration<BlogPost>
    {
        public BlogConfiguration()
        {
            this.ToTable("Blogs");
            this.HasKey(t => t.BlogID);
            this.Property(t => t.BlogID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
 
            this.Property(t => t.Title).IsRequired().HasMaxLength(50).HasColumnType("varchar");
 
            this.Property(t => t.Description).IsRequired().HasMaxLength(222).HasColumnType("nvarchar");
            this.Property(t => t.PostedOn).IsRequired().HasColumnType("datetime");
 
 
            this.HasRequired(t => t.Category)
                .WithMany(t => t.BlogPosts)
                .HasForeignKey(t => t.CategoryID);    
      // "CategoryID is already declared in Blogs" 
            otherwise use .Map(t=>t.MapKey("Give any FK Name"))
                        
                
        }
    } 


 public class CommentConfiguration : EntityTypeConfiguration<Comment>
    {
        public CommentConfiguration()
        {
            this.ToTable("Comment");
            this.HasKey(t => t.CommentID);
            this.Property(t => t.CommentID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            this.Property(t => t.CommentText).HasMaxLength(200).HasColumnType("varchar").IsRequired();
 
            this.HasRequired(t => t.PostedByUser)
                .WithMany(t => t.AllComments)
                .Map(t => t.MapKey("UserID"))
                .WillCascadeOnDelete(false);
 
            this.HasRequired(t => t.Blog)
                .WithMany(t => t.Comments)
                .Map(t => t.MapKey("BlogID"))
                .WillCascadeOnDelete(false);
 
        }
    }
 
---------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------- 

(II).

 public class UsersContext : DbContext
    {
        public UsersContext()  : base("mycon")
        {
 
        }
 
        public DbSet<UserProfile> UserProfiles { getset; }
    }
 
 
 In private class SimpleMembershipInitializer 
 using (var context = new UsersContext())
    {
       if (!context.Database.Exists())
        {
        // Create the SimpleMembership database without Entity Framework migration schema
          ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
        }
    }
 
    if (!WebSecurity.Initialized)
      {
        WebSecurity.InitializeDatabaseConnection("mycon""UserProfile""UserId""UserName",
                                                                       autoCreateTables: true);
      } 
 
 
     protected void Application_Start()
        {
             
         Database.SetInitializer<UsersContext>(null);
         UsersContext context = new UsersContext();
         context.Database.Initialize(true);
     if (!WebSecurity.Initialized)
     WebSecurity.InitializeDatabaseConnection("mycon""UserProfile""UserId""UserName"
                                                                      autoCreateTables: true);
 
         }


0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More