上下文和上下文初始化程序未运行
本文关键字:上下文 运行 初始化 程序 | 更新日期: 2023-09-27 18:29:21
我正在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; }
}
}
您可以将对初始值设定项的调用放在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)方法。
请确保将初始化程序代码放入Global.asax.cs文件中MvcApplication类的受保护的void Application_Start()方法中。
这是一篇关于DropCreateDatabaseAlwaysInitializer的文章。如何在代码先行创建模式下使用实体框架?
@EduLopez是对的,请确保您运行以下
Database.SetInitializer(new AbstractContextInitializer());
在访问上下文之前。
我也不能100%确定,但我认为在你尝试访问上下文之前,种子不会发生。因此,在认为查询不起作用之前,一定要先运行它。