在EF7中加载参考 [英] 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; }
}
和
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),我通过以下方式进行连接:
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);
});
}
}
当我访问博客文章Db.Blogpost.First(x => x.Id == id)
时,我会检索博客文章对象-但是,.Author
属性为null.另外,检索任何Author对象时,其.Blogposts
集合为空.
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.
我知道EF7既没有实现预加载,也没有实现延迟加载.但是我该如何检索/分配通过外键引用的任何对象?
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?
推荐答案
EF 7已实现了预加载.
EF 7 has implemented eager loading.
使用.include
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
这篇关于在EF7中加载参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!