none
Code First: How to Inject script between DB Creation and Model Build-out

    Question

  • I am working on an MVC3 app using EF Code First and asp.net membership services.  Thus my db initialization needs to not only build out the EF models but run the aspnet_reqsql.sql script as well.  Moreover my model contains a type that maps to the aspnet_Users table.  I map this in my db context as follows:

     
           protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                base.OnModelCreating(modelBuilder);
                modelBuilder.Entity<User>()
                    .ToTable("aspnet_Users");
                modelBuilder.Entity<User>()
                    .Property(u => u.Name).HasColumnName("UserName");
                
            }
    

    Originally I had this working by invoking the regsql script at the top of the DatabaseInitializers Seed() method.  I had to add the following SQL to the script to handle the fact that EF would create a aspnet_Users table (but which did not contain all the columns needed by ASP).

    IF NOT Exists(select * from sys.columns where Name = N'ApplicationId'  
                and Object_ID = Object_ID(N'aspnet_Users'))
    BEGIN
    --This indicates the presense of a the table as created by the Entity Framework Code First
    --EF does no create the full schema so just drop it so that the script below will do its job.
        DROP TABLE [dbo].aspnet_Users
    END
    IF NOT Exists(select * from sys.columns where Name = N'ApplicationId'  
                and Object_ID = Object_ID(N'aspnet_Users'))
    BEGIN
    	--This indicates the presense of a the table as created by the Entity Framework Code First
    	--EF does no create the full schema so just drop it so that the script below will do its job.
        DROP TABLE [dbo].aspnet_Users
    END

    This worked fine as a hack until the point where EF code first is now creating FK contraints on the table as well, so the drop command fails.  

    It seems that what I need is a solution that will 1) Allows me to run the reqsql script after the database itself is created and before EF builds out its entities and 2) Allows me to tell EF not to CREATE the aspnet_Users table.  (Though I would like it to create the FK Constrains).

    Any idea how to do this?  I have looked at EF Tips and Tricks and a few similar articles on creating my own initialization strategy but none show how to separate db creation from db build-out.

    Thanks,

    Ken

    Sunday, May 06, 2012 1:42 PM

Answers

  • Fly_fish,

    Your approach seems reasonable but I was hoping a somewhat more direct solution.  Ultimately I implemented a custom initializer strategy and blogged about it here.  

    Sunday, May 20, 2012 2:51 PM

All replies