我有几个相关的实体,我试图用一些虚拟数据为数据库播种。这是我的种子代码:
public class EventInitializer : DropCreateDatabaseAlways<BSContext>
{
protected override void Seed(BSContext context)
{
var authors = new List<Author>
{
new Author { Name = "Christina Gabbitas" },
new Author { Name = "Gemma King" },
new Author { Name = "Gemma Collins"},
new Author { Name = "Billy Hayes" },
new Author { Name = "Jodi Picoult" },
new Author { Name = "John Whaite" }
};
authors.ForEach(a => context.Authors.Add(a));
context.SaveChanges();
var events = new List<Event>
{
new Event { Authors = new List<Author> { context.Authors.Find(0) }, Book = "Felicity Fly", Info = "Christina Gabbitas will be signing copies of her new book, Felicity Fly. Books should be bought from WHSmith. Proof of purchase may be necessary", Start = new DateTime(2013, 05, 25, 10, 30, 00), Url = "http://www.whsmith.co.uk/Support/InStoreSignings.aspx", Location = new Location { Name = "WHSmith Brent Cross", Address = "Brent Cross Shopping Centre", City = "London", County = "", PostCode = "NW4 3FB", Telephone = 02082024226 } },
new Event { Authors = new List<Author> { context.Authors.Find(1) }, Book = "Haunted Spalding", Info = "Gemma King will be signing copies of her new book. Books should be bought from WHSmith. Proof of purchase may be necessary", Start = new DateTime(2013, 03, 31, 10, 00, 00), Url = "http://www.whsmith.co.uk/Support/InStoreSignings.aspx", Location = new Location { Name = "WHSmith Spalding", Address = "6-7 Hall Place", City = "Spalding", County = "Lincolnshire", PostCode = "PE11 1SA", Telephone = 01775768666 } },
new Event { Authors = new List<Author> { context.Authors.Find(3) }, Book = "Midnight Express", Info = "Billy Hayes will be signing copies of his books. Books should be bought from WHSmith. Proof of purchase may be necessary", Start = new DateTime(2013, 04, 13, 13, 00, 00), Url = "http://www.whsmith.co.uk/Support/InStoreSignings.aspx", Location = new Location { Name = "WHSmith Birmingham", Address = "29 Union Street", City = "Birmingham", County = "West Midlands", PostCode = "B2 4LR", Telephone = 01216313303 } }
};
events.ForEach(e => context.Events.Add(e));
context.SaveChanges();
}
}
上面的种子代码与我的所有实体一起位于一个单独的项目中。我这样做是为了让我的域模型与我的Web应用程序完全分开。当然,我的控制器中有引用来访问实体。
我之前使用过EF Code First,但这次它对我不起作用!当我在我的控制器(ASP.NET MVC应用程序)中访问这样的数据时,我得到0结果。
public ActionResult Index()
{
ViewBag.Message = "Move around the map to find events near you.";
var model = new IndexVM();
using(var context = new BSContext())
{
model.Events = (List<Event>)context.Events.ToList();
}
return View(model);
}
我在Windows 8 64x Pro上使用EF(v4.0.30319)和Visual Studio 2012.更糟糕的是,我甚至无法调试!当我尝试在调试模式下运行时,我的断点永远不会被击中!这是我的Web.config用于网络项目。
答案 0 :(得分:0)
您需要像这样致电Database.SetInitializer
:
Database.SetInitializer<BSContext>( new EventInitializer() );