我有两个课程-作者和博客文章:
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
属性为null。另外,检索任何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
有关使用集合的更多信息,请参见以下问题的答案:如何使用集合
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句