简体   繁体   中英

Entity Framework: Navigational properties - Code First

Man I am having a heck of a time today trying to get this to work. I think I'm missing something in terms of a navigational property.

My controller. When I put a breakpoint at foo = 5, and I look at the local watch window, "listOfComments" has zero elements even though my database has the information listed(see below)

public ActionResult CommentsList()
    {
        var post = _db.GetPost(5);
        List<Comment> listOfComments = post.Comments.ToList();
        var foo = 5;
        return View(post);
    }

GetPost method

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;


    }

Comment class

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; }

}

Post class

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; }

}

My DbContext class

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; }


}

The Database table, "Comments" has the following columns:

-Id
-Date
-Name
-Email
-Body
-Post_Id

The Database table, "Posts" has the following columns:

-Id
-Title
-Date
-Body

Just as an example, my Database populates the Comments columns just fine, it adds the right Post_Id referencing the primary key and all. I have the same issue with the Tag table, but that even has it's own reference table:

The Database table, "TagPosts" has the following columns:

-TagId
-PostId

Lost please help!

The Comments collection in the Post class should be virtual if you want to enable lazy loading or you should use Include(p => p.Comments) to load the data with the original query. In general the second option is better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM