数据存储库实例Null-NullReferenceException吗?你调用的对象是空的

时间:2018-09-13 20:22:23

标签: c# asp.net-mvc entity-framework

我在网上看到的所有内容,都应该实例化我的仓库的实例,我相信我已经做完了,但是我仍然收到空引用异常。

这是实现IArticleRepository接口的类。

public class ArticleRepository : IArticleRepository
    {
        private readonly ApplicationDbContext dbContext;
        public ArticleRepository(ApplicationDbContext dbContext)
        {
            this.dbContext = dbContext;
        }

        public void DeleteArticle(int articleId)
        {
            throw new NotImplementedException();
        }

        public async Task<Article> GetArticleAsync(int articleId)
        {
            Article article = await dbContext.Articles.FirstOrDefaultAsync(x => x.Id == articleId);
            return article;
        }

        public async Task<IEnumerable<Article>> GetArticles()
        {
            var articles = await dbContext.Articles.ToListAsync();
            return articles;
        }

        public void InsertArticle(Article article)
        {
            dbContext.Articles.Add(article);
        }

        public async void Save()
        {
            await dbContext.SaveChangesAsync();
        }

        public void UpdateArticle(Article article)
        {
            throw new NotImplementedException();
        }
    }

在我的控制器中,我有:

private readonly ArticleRepository _ArticleRepo;

public ArticleController(){}

public ArticleController(ArticleRepository _ArticleRepo)
{
    this._ArticleRepo = _ArticleRepo;
}

因此,我正在实例化ArticleRepo的实例(希望我做对了)。

[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public ActionResult New (Article article)
{
    try
    {
        if (ModelState.IsValid)
        {
            var userId = User.Identity.GetUserId();

            Article newArticle = new Article
            {
                Title = article.Title,
                Content = article.Content,
                AuthorId = userId,
                CreatedAt = DateTime.Now,
                LastUpdated = DateTime.Now
            };

            _ArticleRepo.InsertArticle(newArticle);
            _ArticleRepo.Save();

            return RedirectToAction("Details", "Article", new { id = article.Id });
        }
    } catch (DataException)
    {
        ModelState.AddModelError(string.Empty, "Unable to save changes. Try again, and if the problem persists contact your system administrator.");
    }

   return View(article);
}

点击_ArticleRepo.InsertArticle(newArticle);时出现错误

0 个答案:

没有答案