In this article, I’ll explain how to implement sample BlogContext for EF Code First DbContext and database initializer setting.
Web.config connection setting
Let’s change the connectionStrings section of Web.config file. At default, we will use SqlCE for our database. We also change easily MS-SQL database by changing connection string below.
<connectionStrings>
<!--<add name="BlogContext"
connectionString="Data Source=localhost;
Initial Catalog=MvcBlog;
Persist Security Info=True;
User ID=sa;Password=12345;"
providerName="System.Data.SqlClient" />-->
<add name="BlogContext"
connectionString="data source=|DataDirectory|\MvcBlog.sdf"
providerName="System.Data.SqlServerCe.4.0" />
</connectionStrings>
Model and DbContext Definition
For simple blog system, let’s design three model classes.
public class Post
{
public int Id { get; set; }
[Required][MaxLength(128)]
public string UserName { get; set; }
[Required][MaxLength(128)]
public string Title { get; set; }
[MaxLength(256)]
public string ImageUrl { get; set; }
[Required][MaxLength(256)]
public string Summary { get; set; }
[Required]
public string Content { get; set; }
public int CommentCount { get; set; }
public DateTime DateCreated { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
public virtual ICollection<Term> Terms { get; set; }
}
public class Comment
{
public int Id { get; set; }
[MaxLength(128)]
public string UserName { get; set; }
[MaxLength(128)]
public string Author { get; set; }
[MaxLength(128)]
public string AuthorEmail { get; set; }
[MaxLength(256)]
public string AuthorUrl { get; set; }
[MaxLength(128)]
public string AuthorIp { get; set; }
[Required]
public string Content { get; set; }
public DateTime DateCreated { get; set; }
public Nullable<int> ParentCommentId { get; set; }
public virtual Comment Parent { get; set; }
public int PostId { get; set; }
public virtual Post Post { get; set; }
public virtual ICollection<Comment> Children { get; set; }
}
public class Term
{
public int Id { get; set; }
[Required][MaxLength(128)]
public string Name { get; set; }
public bool IsClip { get; set; }
[Required][MaxLength(256)]
public string Summary { get; set; }
public Nullable<int> ParentTermId { get; set; }
public virtual Term Parent { get; set; }
public virtual ICollection<Term> Children { get; set; }
public virtual ICollection<Post> Posts { get; set; }
}
Let’s define BlogContext by inheriting DbContext of EF 4.1.
public class BlogContext : DbContext
{
public IDbSet<Post> Posts { get; set; }
public IDbSet<Comment> Comments { get; set; }
public IDbSet<Term> Terms { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
Let’s create BlogDataInitializer class for default data setup.
public class BlogDataInitializer : DropCreateDatabaseIfModelChanges<BlogContext>
{
protected override void Seed(BlogContext context)
{
var terms = new List<Term>
{
new Term { Name = ".NET", Summary = ".NET Summary" },
...
};
var posts = new List<Post>
{
new Post { UserName = "user1", Title = "MVC3 Overview", Summary = "Summary 1", Content = "Writing 1",
DateCreated = DateTime.Parse("2005-09-01"),Terms = new List<Term>{ terms[0], terms[1]}},
...
};
terms.ForEach(t => context.Terms.Add(t));
posts.ForEach(p => context.Posts.Add(p));
}
}
Register BlogDataInitializer class to Global.asax
protected void Application_Start()
{
...
Database.SetInitializer(new BlogDataInitializer());
}
Running for test
Let’s add List action method to HomeController to quick test.
public class HomeController : Controller
{
private readonly BlogContext context = new BlogContext();
public ActionResult List()
{
var list = context.Posts.ToList();
return View(list);
}
...
}OK. Let’s check the result.
We can see full featured database schema including self referencing relation and auto generated many to many mapping table called ‘TermPost’.
Conclusion
Through the EF Code First and Database Initializer, we can always setup easily our default database and data records.