Pet*_*ert 6 entity-framework-core asp.net-core-mvc
我有两个课程 - 作者和博客:
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; }
}
Run Code Online (Sandbox Code Playgroud)
和
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; }
}
Run Code Online (Sandbox Code Playgroud)
使用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);
});
}
}
Run Code Online (Sandbox Code Playgroud)
当我访问博客Db.Blogpost.First(x => x.Id == id)
帖子时,我检索了Blogpost对象 - 但是,该.Author
属性为null.此外,在检索任何Author对象时,它的.Blogposts
集合为空.
我知道EF7既没有实现预先加载也没有延迟加载.但是,我如何检索/分配通过外键引用的任何对象?
nat*_*ter 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
Run Code Online (Sandbox Code Playgroud)
有关使用集合的更多信息,请参阅此问题的答案:如何使用集合
归档时间: |
|
查看次数: |
3377 次 |
最近记录: |