我正在我的MVC网站上尝试代码优先开发,虽然global.ascx文件正在运行代码来创建一个新的初始化程序,但初始化程序本身并没有运行。我在上下文的开头和初始化程序都设置了断点,两者都没有被击中。
Global.ascx
Database.SetInitializer<AbstractContext>(new AbstractContextInitializer());
上下文:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace AbstractThinking2015.Models
{
public class AbstractContext : DbContext
{
public DbSet<BlogModel> Blogs { get; set; }
}
}
初始化器:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace AbstractThinking2015.Models
{
public class AbstractContextInitializer : DropCreateDatabaseAlways<AbstractContext>
{
protected override void Seed(AbstractContext context)
{
context.Blogs.Add(
new BlogModel() { Title = "Test Title",
Date = DateTime.Now,
User = "Liane",
Category = "Test",
Post = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus rhoncus tristique leo et vehicula. Integer eu imperdiet orci, sit amet convallis ipsum. Sed in commodo urna. Sed venenatis neque augue, et faucibus purus aliquet eget. Suspendisse nec sapien nec justo ullamcorper rutrum. Praesent maximus nulla eget rhoncus scelerisque. Vivamus at felis porta, placerat augue non, interdum dui."
});
context.SaveChanges();
}
}
}
以防万一,这是模特:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace AbstractThinking2015.Models
{
public class BlogModel
{
//public BlogModel()
//{
// Date = DateTime.Now;
// User = "Liane";
//}
public int BlogModelId { get; set; }
[DisplayName("Blog Title")]
[Required(ErrorMessage = "Your blog must have a title")]
public string Title { get; set; }
[DisplayName("Blog Date")]
[Required(ErrorMessage = "Your blog must have a date")]
public DateTime Date { get; set; }
[DisplayName("Blog User")]
[Required(ErrorMessage = "Your blog must have a user")]
public string User { get; set; }
[DisplayName("Blog Category")]
[Required(ErrorMessage = "Your blog must have a category")]
public string Category { get; set; }
[DisplayName("Blog Post")]
[Required(ErrorMessage = "Your blog must have a post")]
[DataType(DataType.MultilineText)]
public string Post { get; set; }
}
}
答案 0 :(得分:1)
您可以在DbContext类中调用初始化程序,如下所示:
Public Class AuctionsDataContext
Inherits DbContext
Public Property Auctions As DbSet(Of Auction)
Public Property Bids As DbSet(Of Bid)
Shared Sub New()
Database.SetInitializer(New DropCreateDatabaseIfModelChanges(Of AuctionsDataContext))
End Sub
End Class
请注意,构造函数需要定义为静态(C#)或共享(VB)方法。
答案 1 :(得分:0)
确保将初始化程序代码放在Global.asax.cs文件中MvcApplication类的protected void Application_Start()方法中。
答案 2 :(得分:0)
这是关于DropCreateDatabaseAlwaysInitializer的帖子。 How do I use Entity Framework in Code First Drop-Create mode?
@EduLopez是对的,请确保运行以下内容
Database.SetInitializer(new AbstractContextInitializer());
在访问上下文之前。
我也不是百分百肯定,但我认为在您尝试访问上下文之前不会播种。因此,请确保在认为查询无效之前运行查询。