男人今天我正忙着努力让它发挥作用。我想我在导航财产方面缺少一些东西。
我的控制器。当我在foo = 5处设置断点时,我会查看本地监视窗口," listOfComments"即使我的数据库列出了信息(见下文)
,也没有元素public ActionResult CommentsList()
{
var post = _db.GetPost(5);
List<Comment> listOfComments = post.Comments.ToList();
var foo = 5;
return View(post);
}
GetPost方法
public Post GetPost(int? postId)
{
var context = DataContext;
var post = context.Posts.FirstOrDefault(x => x.Id == postId);
if (post == null)
{
return new Post();
}
return post;
}
评论课
public class Comment
{
public int Id { get; set; }
[Required]
public DateTime Date { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Email { get; set; }
[Required]
public string Body { get; set; }
//Navigational
public Post Post { get; set; }
}
发布课程
public class Post
{
public Post()
{
Comments = new HashSet<Comment>();
Tags = new HashSet<Tag>();
}
public int Id { get; set; }
[Required]
public string Title { get; set; }
[Required]
public DateTime Date { get; set; }
[Required]
public string Body { get; set; }
//Navigational
public ICollection<Comment> Comments { get; set; }
public ICollection<Tag> Tags { get; set; }
}
我的DbContext类
public class HundredBlog: DbContext
{
public HundredBlog() : base("HundredBlog") { }
public DbSet<Post> Posts { get; set; }
public DbSet<Comment> Comments { get; set; }
public DbSet<Administrator> Administrators { get; set; }
public DbSet<Tag> Tags { get; set; }
}
数据库表,&#34;评论&#34;有以下列:
-Id
-Date
-Name
-Email
-Body
-Post_Id
数据库表,&#34;帖子&#34;有以下列:
-Id
-Title
-Date
-Body
就像一个例子,我的数据库填充了Comments列,它添加了正确的Post_Id引用主键和所有。我对Tag表有同样的问题,但它甚至拥有它自己的引用表:
数据库表,&#34; TagPosts&#34;有以下列:
-TagId
-PostId
失去了请帮助!
答案 0 :(得分:2)
如果要启用延迟加载,Post类中的Comments集合应该是虚拟的,或者您应该使用Include(p => p.Comments)
使用原始查询加载数据。一般来说,第二种选择更好。