在EF7中加載引用

asp.net-core-mvc entity-framework-core

我有兩個課程 - 作者和博客:

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

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

使用EF7(beta4),我按以下方式連接它們:

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

當我訪問博客帖子Db.Blogpost.First(x => x.Id == id)檢索到博客帖子對象-然而,所述.Author屬性為null。此外,在檢索任何Author對象時,它的.Blogposts集合為空。

據我所知,EF7既未實現預先加載也未實現延遲加載。但是,我如何檢索/分配通過外鍵引用的任何對象?

一般承認的答案

EF 7實現了預先加載。

使用.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

有關使用集合的更多信息,請參閱此問題的答案: 如何使用集合



Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow