我有两个类(class) - 作者和博客文章:
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)
我检索 Blogpost 对象 - 但是,.Author
属性一片空白。此外,当检索任何 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
有关使用集合的更多信息,请参阅此问题的答案:How to work with collections
关于asp.net-core-mvc - 在 EF7 中加载引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30192872/