启动dropcreatedatabase
时,我遇到了播种某些常量数据的问题。我查看了一些类似的问题,但我很难理解为什么我的代码无效。
非常感谢所有帮助(c:
这是我的带有种子数据的SampleData模型
public class SampleData : DropCreateDatabaseIfModelChanges<fotmEntities>
{
protected override void Seed(fotmEntities context)
{
var genres = new List<Genre>
{
new Genre { Name = "Specials" },
new Genre { Name = "Online" },
new Genre { Name = "Services" },
new Genre { Name = "Food" },
new Genre { Name = "Misc" },
new Genre { Name = "Auto" }
};var localities = new List<Locality>
{
new Locality { Name = "Location1" },
new Locality { Name = "Location2" },
new Locality { Name = "Location3" },
new Locality { Name = "Location4" },
};
new List<Discount>
{
new Discount { Title = "Title A", Genre = genres.SingleOrDefault(g => g.Name == "Specials"), Information = "8.99M", Locality = localities.Single(a => a.Name == "Location1"), DiscountArtUrl = "/Content/img/placeholder.gif" },
new Discount { Title = "Title B", Genre = genres.SingleOrDefault(g => g.Name == "Specials"), Information = "8.99M", Locality = localities.Single(a => a.Name == "Location2"), DiscountArtUrl = "/Content/img/placeholder.gif" },
new Discount { Title = "Title C", Genre = genres.SingleOrDefault(g => g.Name == "Services"), Information = "8.99M", Locality = localities.Single(a => a.Name == "Location3"), DiscountArtUrl = "/Content/img/placeholder.gif" },
new Discount { Title = "Title D", Genre = genres.SingleOrDefault(g => g.Name == "Food"), Information = "8.99M", Locality = localities.Single(a => a.Name == "Location4"), DiscountArtUrl = "/Content/img/placeholder.gif" },
new Discount { Title = "Title E", Genre = genres.SingleOrDefault(g => g.Name == "Misc"), Information = "8.99M", Locality = localities.Single(a => a.Name == "Location1"), DiscountArtUrl = "/Content/img/placeholder.gif" },
new Discount { Title = "Title F", Genre = genres.SingleOrDefault(g => g.Name == "Auto"), Information = "8.99M", Locality = localities.Single(a => a.Name == "Location2"), DiscountArtUrl = "/Content/img/placeholder.gif" },
}.ForEach(a => context.Discounts.Add(a));
这是我的上下文模型:
using System.Data.Entity;
public class fotmEntities : DbContext
{
public DbSet<Discount> Discounts { get; set; }
public DbSet<Genre> Genres { get; set; }
public DbSet<Locality> Localities { get; set; }
}
和我的Global.asx
protected void Application_Start()
{
System.Data.Entity.Database.SetInitializer(
new fotm.Models.SampleData());
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}