Beetlejuice
Beetlejuice

Reputation: 4425

Entity Framework 7 RC1 relations

Now that I updated to ASP.NET 5 RC1, and Entity Framework 7 RC1, I expected to have relations enabled in my models. But I can't get this to work.

Here are my models:

Post:

public class Post
{
    public int Id { get; set; }
    public string Text { get; set; }

    public virtual ICollection<Comment> Comments { get; set; }
}

Comment:

public class Comment
{
    public int Id { get; set; }
    public string Text { get; set; }

    public int PostId { get; set; }
    public virtual Post Post { get; set; }
}

I have inserted manually some data in the tables and tried to access Comments property of a post like this:

var post = context.Posts.Where(x => x.Id == 1).FirstOrDefault();

var sb = new StringBuilder();
foreach(var comment in post.Comments)
{
    sb.Append(comment.Text);
}

but the Comments property is always null. This post has two comments in table.

What I'm doing wrong?

Upvotes: 1

Views: 126

Answers (1)

DavidG
DavidG

Reputation: 118937

Entity Framework 7 doesn't support lazy loading (but it is on the roadmap) so you need to Include your child relations:

var post = context
    .Posts
    .Include(p => p.Comments)
    .Where(x => x.Id == 1).FirstOrDefault();

Upvotes: 5

Related Questions