![](/img/trans.png)
[英]Multidimensional navigational properties in Entity Framework 6 Code First
[英]Entity Framework: Navigational properties - Code First
老兄,我今天很忙,试图使它正常工作。 我认为我在导航属性方面缺少一些东西。
我的控制器。 当我在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; }
}
数据库表“注释”具有以下列:
-Id
-Date
-Name
-Email
-Body
-Post_Id
数据库表“帖子”具有以下列:
-Id
-Title
-Date
-Body
举个例子,我的数据库很好地填充了Comments列,它添加了引用主键和全部的正确的Post_Id。 Tag表存在相同的问题,但是它甚至拥有自己的引用表:
数据库表“ TagPosts”具有以下列:
-TagId
-PostId
迷路请帮忙!
如果要启用延迟加载,则Post类中的Comments集合应该是虚拟的,或者应该使用Include(p => p.Comments)
来使用原始查询加载数据。 通常,第二种选择更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.