Eranga Dissanayaka
Eranga Dissanayaka

Reputation: 1930

EFCodeFirst - Initialize DB and create tables


Is there a way to create the tables through a SQL script when the database is initialized in EFCodeFirst approach. ( I mean, to avoid auto table creation and use my custom script instaead for table creation).

I've tried below approach, but it doesn't seem to be creating the table as per the SQL script. context.Database.ExecuteSqlCommand is supposed to work for DDL SQL as well as DML SQL.

class Class1
{

    public void InitializeDB()
    {
        Database.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");

        var dbInitializer = new DbInitializer();
        Database.SetInitializer(dbInitializer);
        var target = new MyDbContext();
        target.Database.Initialize(true);
    }
}

public class DbInitializer : DropCreateDatabaseAlways<MyDbContext>
{
    private string CreateTableSQL = "CREATE TABLE [dbo].[UserLogins](" +
                         "[UserId] [int] IDENTITY(1,1) NOT NULL," +
                         "[UserName] [varchar](100) NOT NULL," +
                         "[FirstName] [nvarchar](200) NULL," +
                         "[LastName] [nvarchar](200) NULL )";

    public void InitializeDatabase(MyDbContext context)
    {
        context.Database.ExecuteSqlCommand(CreateTableSQL, string.Empty);
    }
}

Upvotes: 1

Views: 799

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364259

If you inherit DropCreateDatabaseAlways you cannot change InitializeDatabase logic because that method is not virtual. Instead of inheriting DropCreateDatabaseAlways implement IDatabaseInitializer directly.

Upvotes: 4

Related Questions