Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to change database with Entity Code First in ASP.NET MVC3

0.00/5 (No votes)
8 Jan 2013 1  
A website application with ASP.NET MVC3 for my blog http://truongminhtuan.info.

While implementing a project with Entity Code First, I found out an interesting thing to share. In the project I made a personal blog. Here I create a class that contains the attributes, in this case a Table

I create a class Article with properties, including:

public class Article
{
    //[Key]
    public int ArticleId { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    [Required]
    [Column(TypeName = "ntext")]
    [MaxLength]
    public string Content { get; set; }

    private DateTime _datetime = DateTime.Now;
    public DateTime DateTime {
        get { return _datetime; } set { _datetime=value;} 
    }
    public int Hot { get; set; }
    public string AccountId { get; set; }
    public int CategoryId { get; set; }
    public int Active { get; set; }
}

Next, I create a DbContext for generating class Article into Table Article:

public DbSet<Article> Article { get; set; }

Then, I change in Global for section Application_Start:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RegisterGlobalFilters(GlobalFilters.Filters);

    RegisterRoutes(RouteTable.Routes);
    Database.SetInitializer<BlogContext>(null);            
}

Then press F5 for run project.

Happy coding!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here