I’m playing around with ASP.NET MVC 3 + EF Code First. At a testing stage my models change often. To always have some clean content when building and running the project I have overridden the Seed method in my custom database initializer class (inherit from DropCreateDatabaseIfModelChanges<T>).
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using Test.Models;
namespace Test.DAL
{
public class TestInitializer : DropCreateDatabaseIfModelChanges<TestContext>
{
protected override void Seed(TestContext context)
{
var categories = new List<ProductCat>
{
new ProductCat { Name = "Wood" },
new ProductCat { Name = "Metal" },
new ProductCat { Name = "Plastic" }
};
var products = new List<Product>
{
new Product { Name = "Bench", ProductCat = categories.Single(c => c.Name == "Wood")},
new Product { Name = "Bottle", ProductCat = categories.Single(c => c.Name == "Plastic")},
new Product { Name = "Electric cable", ProductCat = categories.Single(c => c.Name == "Metal")}
};
products.ForEach(p => context.Products.Add(p));
context.SaveChanges();
base.Seed(context);
}
}
}
Now if you have SQL Server Management Studio (SSMS) open, you will see that your generated database is something like Project.Namespace.Class, which is actually not a good name. To change that EF Code First generated name you can do something like this in your DbContext class:
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace Test.Models
{
public class TestContext : DbContext
{
public TestContext()
: base("MyNewDBName") // <-- database name
{ }
public DbSet<Product> Products { get; set; }
public DbSet<ProductCat> Categories { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
Keep in mind that this is only one of the places where you can change the default database name.
Now your database will be called MyNewDBName in SSMS.
Have fun ;-)