Download links in EF7

I have 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 link them as follows:

 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 blogpost Db.Blogpost.First(x => x.Id == id) , I retrieve the Blogpost object, but the .Author property is null. Also, when receiving any Author object, it .Blogposts not empty.

I understand that EF7 has not yet implemented boot loading and non-lazy loading. But how would I then retrieve / assign any objects referenced by the foreign key?

+6
source share
1 answer

EF 7 implemented an active download.

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 about working with collections, see the answer to this question: How to work with collections

+10
source

Source: https://habr.com/ru/post/987057/


All Articles