我有一个启用了代码优先迁移的ASP MVC 5 Web应用程序。我有两个名为Post.cs和PostSubject.cs的表/类。
Post.cs
public class Post
{
public int Id { get; set; }
[Required(ErrorMessage="Title is required")]
[MaxLength(255,ErrorMessage="Title too long")]
public string Title { get; set; }
[MaxLength(1023,ErrorMessage="Description too long")]
[Required(ErrorMessage = "Description is required")]
public string Description { get; set; }
public PostSubject PostSubject { get; set; }
[Display(Name="Stream")]
[Required(ErrorMessage="Choose a Stream")]
public int PostSubjectId { get; set; }
[NotMapped]
public HttpPostedFileBase Attachment { get; set; }
}
PostSubject.cs
public class PostSubject
{
public short Id { get; set; }
public string SubjectName { get; set; }
}
我正在尝试将所有帖子及其PostSubjects加载到索引视图中。
索引操作
[HttpGet]
public ActionResult Index()
{
var contributions =_context.Posts.Include(m=>m.PostSubject).ToList();
return View(contributions);
}
索引HTML
@model IEnumerable<Cluster_University.Models.Post>
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<table>
<tr>
<td>Title</td>
<td>Descripttion</td>
<td>Subject</td>
</tr>
@foreach (var posts in Model)
{
<tr>
<td>@posts.Title</td>
<td>@posts.Description</td>
<td>@posts.PostSubject.SubjectName</td>
</tr>
}
</table>
问题:@ Posts.PostSubject.SubjectName出现空引用错误
请让我理解代码中的问题。