I am getting a NullReferenceException on an object which is not null I have a model of name articles in my entity framework db. Below is the model class
public class Articles
{
[Key]
public int Id { get; set; }
[Required(ErrorMessage = "Title is needed")]
public string Title { get; set; }
[Required(ErrorMessage = "Author is needed")]
public ApplicationUser Author { get; set; }
[Required(ErrorMessage = "Content is needed")]
[Display(Name ="Content")]
public string Content { get; set; }
[Required(ErrorMessage = "Subject is needed")]
public string Subject { get; set; }
}
Below is the action where I am trying to retrieve the Author
[HttpGet]
public async Task<IActionResult> ListArticles()
{
var query = from a in this.context.articles select a;
string id = string.Empty;
foreach (var q in query)
{
id = q.Author.ToString();//THIS WHERE I AM GETTING NullReferenceException
return View(query);
}
}
Here is the view snippet for this controller action
@foreach(var m in Model)
{
<div class="card-body">
<div class="row">
<div class="col">
<a href="#" class="nav-link">@m.Title</a>
</div>
</div>
<div class="row">
<div class="col-md-6">By: @user</div>
<div class="col-md-6">Subject: @m.Subject</div>
</div>
</div>
</div>
}
PS: Why did the Author field turned to AuthorId in the model?
Here is the ApplicationUser class (Type of Author in the model class)
public class ApplicationUser : IdentityUser
{
public string Firstname { get; set; }
public string Lastname { get; set; }
public bool isUser { get; set; }
public bool isAuthor { get; set; }
public bool isAdmin { get; set; }
}
Forgive me If there is a silly mistake I am very new to asp.net mvc