Search code examples
entity-frameworkcode-first

Code First : Context fields are null


Here is my context:

public class ContentContext : DbContext
{
    public ContentContext() : base("Name=CodeFirstDatabase") {  }

    public DbSet<Article> Articles;
    public DbSet<ArticleTag> ArticleTags;
}

connection string:

<add name="CodeFirstDatabase" providerName="System.Data.SqlClient" connectionString="Server=X-ПК\SQLEXPRESS;Database=Products;Trusted_Connection=true;"/>

Global.asax:

Database.SetInitializer(new CreateDatabaseIfNotExists<ContentContext>());

HomeController:

    public ActionResult Index()
    {
       ContentContext context = new ContentContext();
       context.Database.Initialize(true);

       Article a = new Article() { Text = "TEXT" };

       context.Articles.Add(a);
       context.SaveChanges();

       return View();
    }

Entities:

public class Article
{
    public int Id { get; set; }
    public string Author { get; set; }
    public string Text { get; set; }
    public virtual ICollection<ArticleTag> ArticleTags { get; set; }

}

public class ArticleTag
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual Article Article { get; set; }
}

Database created as expected.But no tables created in it and I get null reference exception when I try add new Article. Any ideas? Thanks.


Solution

  • Change your DBSet<> in ContentContext to properties (instead of fields):

    public DbSet<Article> Articles { get; set; }
    public DbSet<ArticleTag> ArticleTags  { get; set; }