Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Change database name created by Code First

0.00/5 (No votes)
17 Apr 2012 1  
Let's see how to define our own database name using Entity Framework Code First

Introduction

If you are trying to use Code First, you should have seen the database name used by default is not always very useful and you surely want to rename it to use something easier. To do that, you simply have to modify your Context class to use the name you've choosen. Here is a simple MyContext class:

public class MyContext : DbContext
{
    public DbSet<Person> Persons { get; set; }
    public DbSet<Project> Projects { get; set; }
    public DbSet<Task> Tasks { get; set; } 

    public MyContext()
    {}

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<Task>().HasRequired(t => t.Project).WithMany(
              p => p.Tasks).HasForeignKey(t => t.ProjectId).WillCascadeOnDelete(false);
        modelBuilder.Entity<Task>().HasRequired(p => p.AssignedTo);
        modelBuilder.Entity<Person>().Property(d => d.BirthDate).HasColumnName("Birth");
        modelBuilder.Entity<Project>().Property(p => p.Name).HasMaxLength(255).IsRequired();
        modelBuilder.Entity<Project>().HasRequired(p => p.Manager);
    }
}

This code will generate a database named EFFirstSample.MyContext. To change the database name I just do this little tweak:

public class MyContext : DbContext
{
    public DbSet<Person> Persons { get; set; }
    public DbSet<Project> Projects { get; set; }
    public DbSet<Task> Tasks { get; set; } 

    public MyContext():base("EFSample")
    {}

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<Task>().HasRequired(t => t.Project).WithMany(p => p.Tasks).HasForeignKey(t => t.ProjectId).WillCascadeOnDelete(false);
        modelBuilder.Entity<Task>().HasRequired(p => p.AssignedTo);
        modelBuilder.Entity<Person>().Property(d => d.BirthDate).HasColumnName("Birth");
        modelBuilder.Entity<Project>().Property(p => p.Name).HasMaxLength(255).IsRequired();
        modelBuilder.Entity<Project>().HasRequired(p => p.Manager);
    }
}

If I run my application, a new database will be created, named EFSample. It's very simple, there is nothing more to add or to do. Hope it helps.

History

  • April, 2012 : First post.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here