我有两个班级 - 作者和博客:
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);
});
}
}
当我访问blogpost Db.Blogpost.First(x => x.Id == id)
时,我检索了Blogpost对象 - 但是,.Author
属性为null。此外,在检索任何作者对象时,它的.Blogposts
集合为空。
我知道EF7既没有实现预先加载也没有实现延迟加载。但是,我如何检索/分配通过外键引用的任何对象?
答案 0 :(得分:10)
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
有关使用集合的详细信息,请参阅此问题的答案:How to work with collections