Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading of references in EF7

I'm having two classes - author and blogpost:

public class Author
{
    public Author()
    {
        Blogposts = new HashSet<Blogpost>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Blogpost> Blogposts { get; set; }
}

and

public class Blogpost
{
    public Blogpost()
    {
    }

    // Properties
    public int Id { get; set; }
    public string Text { get; set; }

    public int AuthorId { get; set; }

    public Author Author { get; set; }
}

Using EF7 (beta4), I'm connecting them the following way:

public partial class MyDbContext : DbContext
{
    public virtual DbSet<Author> Author { get; set; }
    public virtual DbSet<Blogpost> Blogpost { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Author>(entity =>
            {
                entity.Property(e => e.Id)
                    .ForSqlServer().UseIdentity();
            });

            modelBuilder.Entity<Blogpost>(entity =>
            {
                entity.Property(e => e.Id)
                    .ForSqlServer().UseIdentity();
            });

            modelBuilder.Entity<Blogpost>(entity =>
            {
                entity.Reference<Author>(d => d.Author).InverseCollection(p => p.Blogposts).ForeignKey(d => d.AuthorId);
            });
    }
}

When I access a blogpost Db.Blogpost.First(x => x.Id == id) I retrieve the Blogpost object - however, the .Author property is null. Also, when retrieving any Author object, it's .Blogposts collection is empty.

I understand the EF7 has neither implemented eager-loading nor lazy-loading yet. But how would I then retrieve/assign any objects referenced via foreign key?

like image 282
Peter Albert Avatar asked May 12 '15 13:05

Peter Albert


Video Answer


1 Answers

EF 7 has implemented eager loading.

Use .Include

var post = context.Blogpost.First(); // post.Author will be null

var post = context.Blogpost.Include(b => b.Author).First(); // post.Author will be loaded

For more information on working with collections, see the answer to this question: How to work with collections

like image 170
natemcmaster Avatar answered Oct 12 '22 22:10

natemcmaster