I'm pretty new to using Entity Framework, as well as to using ASP.NET MVC. I've been able to complete a couple of tutorials on the ASP.NET MVC website and thought I would start my own project based on the MVC Music Store application.
I can't tell where I went wrong (it all looks the same to me), but for some reason my seed data isn't creating the database.
Item class:
namespace MySite.Models
{
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
}
}
Tag class:
namespace MySite.Models
{
public class Tag
{
public int Id { get; set; }
public string Name { get; set; }
}
}
ItemTag class:
namespace MySite.Models
{
public class ItemTag
{
public int Id { get; set; }
public int ItemId { get; set; }
public int TagId { get; set; }
}
}
MySiteEntities class:
namespace MySite.Models
{
public class MySiteEntities : DbContext
{
public DbSet<Item> Items { get; set; }
public DbSet<Tag> Tags { get; set; }
public DbSet<ItemTag> ItemTags { get; set; }
}
}
Global.asax class:
namespace MySite
{
public class MvcApplication : System.Web.HttpApplication
{
...
protected void Application_Start()
{
System.Data.Entity.Database.SetInitializer(new MySite.Models.SampleData());
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
}
Web.config file:
<configuration>
...
<connectionStrings>
<add name="MySiteEntities"
connectionString="Data Source=|DataDirectory|MySite.sdf"
providerName="System.Data.SqlServerCe.4.0" />
</connectionStrings>
</configuration>
SampleData class:
namespace MySite.Models
{
public class SampleData : DropCreateDatabaseIfModelChanges<MySiteEntities>
{
protected override void Seed(MySiteEntities context)
{
new List<Item>
{
new Item { Id = 1, Name = "Bob Jones" },
new Item { Id = 2, Name = "George Smith" },
new Item { Id = 3, Name = "Boys and Girls" },
new Item { Id = 4, Name = "The President's Hair" },
new Item { Id = 5, Name = "Invaders From Mars" },
new Item { Id = 6, Name = "Tank Shooter" },
new Item { Id = 7, Name = "Stew's Blog" },
new Item { Id = 8, Name = "Social Mania" }
}.ForEach(i => context.Items.Add(i));
new List<Tag>
{
new Tag { Id = 1, Name = "Author" },
new Tag { Id = 2, Name = "Movie" },
new Tag { Id = 3, Name = "Video Game" },
new Tag { Id = 4, Name = "Website" }
}.ForEach(t => context.Tags.Add(t));
new List<ItemTag>
{
new ItemTag { Id = 1, ItemId = 1, TagId = 1 },
new ItemTag { Id = 2, ItemId = 2, TagId = 1 },
new ItemTag { Id = 3, ItemId = 3, TagId = 2 },
new ItemTag { Id = 4, ItemId = 4, TagId = 2 },
new ItemTag { Id = 5, ItemId = 5, TagId = 3 },
new ItemTag { Id = 6, ItemId = 6, TagId = 3 },
new ItemTag { Id = 7, ItemId = 7, TagId = 4 },
new ItemTag { Id = 8, ItemId = 8, TagId = 4 }
}.ForEach(x => context.ItemTags.Add(x));
}
}
}
That's pretty much everything. I did delete the database file at one point. Shouldn't it get created again when I build the solution?