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.