0

这是我的背景:

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

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

连接字符串:

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

全球.asax:

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

家庭控制器:

    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();
    }

实体:

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; }
}

数据库按预期创建。但没有在其中创建表,当我尝试添加新文章时出现空引用异常。有任何想法吗?谢谢。

4

1 回答 1

1

更改您DBSet<>ContentContext属性(而不是字段):

public DbSet<Article> Articles { get; set; }
public DbSet<ArticleTag> ArticleTags  { get; set; }
于 2013-04-06T20:06:26.967 回答