加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-core-mvc – 在EF7中加载引用

发布时间:2020-12-15 20:38:43 所属栏目:asp.Net 来源:网络整理
导读:我有两个课程 – 作者和博客: public class Author{ public Author() { Blogposts = new HashSetBlogpost(); } public int Id { get; set; } public string Name { get; set; } public virtual ICollectionBlogpost Blogposts { get; set; }} 和 public cla
我有两个课程 – 作者和博客:
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

有关使用集合的更多信息,请参阅此问题的答案:How to work with collections

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读