Все, что я видел в Интернете, я должен создать экземпляр моего репо, что, я думаю, я уже сделал, но я все еще получаю исключение нулевой ссылки.
Вот класс, который реализует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);