Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 7 relations [duplicate]

I´m using the example bellow, from http://ef.readthedocs.org/en/latest/getting-started/aspnet5.html, to test asp.net 5 and EF7:

using Microsoft.Data.Entity;
using System.Collections.Generic;

namespace EFGetStarted.AspNet5.Models
{
    public class BloggingContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
        public DbSet<Post> Posts { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            // Make Blog.Url required
            modelBuilder.Entity<Blog>()
                .Property(b => b.Url)
                .Required();
        }
    }

    public class Blog
    {
        public int BlogId { get; set; }
        public string Url { get; set; }

        public List<Post> Posts { get; set; }
    }

    public class Post
    {
        public int PostId { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }

        public int BlogId { get; set; }
        public Blog Blog { get; set; }
    }
}

But in my test, the

public List<Post> Posts { get; set; }

is always null. This look to be obvious because it is not instantiate.

What I have to do to get a behavior like

myBlog.Posts

and get all the posts from this blog ?

like image 467
Beetlejuice Avatar asked May 22 '26 13:05

Beetlejuice


1 Answers

You should specify the virtual keyword for navigation properties. It's because EF creates proxy objects (i.e. inheritors of your classes) to implement lazy-loading. These inheritors can override your virtual properties only:

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public virtual List<Post> Posts { get; set; }
}

Alternatively you can explicitly enumerate tables/classes to include to result set:

// This statement fills Posts property:
var blog = dbContext.Blogs.Include(x => x.Posts).FirstOrDefault(x => x.Id == id);
like image 98
Mark Shevchenko Avatar answered May 25 '26 06:05

Mark Shevchenko