我有两门课——作者和博文:
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属性为空.此外,当检索任何 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 中加载引用
发布评论