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

前端之家收集整理的这篇文章主要介绍了asp.net-core-mvc – 在EF7中加载引用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有两个课程 – 作者和博客
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

原文链接:https://www.f2er.com/aspnet/245685.html

猜你在找的asp.Net相关文章