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

标签 asp.net-core-mvc entity-framework-core

我有两个类(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/

相关文章:

visual-studio - Docker 在 Visual Studio 2017 中失败,如何让 docker 在 VS2017 中运行

c# - 在 x86 模式下构建 MVC6/ASP.Net 5 项目

asp.net-core - asp.net core 中的剑道配置

c# - 添加相关实体时报错 "Database operation expected to affect 1 row(s) but actually affected 0 row(s)"

c# - 使用 OwnsOne() 时,“FromSqlRaw 或 FromSqlInterpolated 是使用不可组合的 SQL 调用的,并在其上组合了一个查询”

c# - 使用平均值返回 "The sequence has no elements"

c# - .Net Core获取ApplicationUser的对象

asp.net-mvc - 如何在 ASP.NET Core MVC Razor 页面的布局层次结构中正确使用部分?

c# - 找不到类型或命名空间名称 'DbEntityEntry<TEntity>'

.net-core - Entity Framework 核心 : How to get the Connection from the DbContext?