我在网上看到的所有内容,都应该实例化我的仓库的实例,我相信我已经做完了,但是我仍然收到空引用异常。
这是实现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);
时出现错误