在EF7中加载参考

编程入门 行业动态 更新时间:2024-10-15 02:32:38
本文介绍了在EF7中加载参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有两个班级-作者和博客文章:

I'm having two classes - author and blogpost:

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),我通过以下方式进行连接:

Using EF7 (beta4), I'm connecting them the following way:

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)时,我会检索博客文章对象-但是,.Author属性为null.另外,检索任何Author对象时,其.Blogposts集合为空.

When I access a blogpost Db.Blogpost.First(x => x.Id == id) I retrieve the Blogpost object - however, the .Author property is null. Also, when retrieving any Author object, it's .Blogposts collection is empty.

我知道EF7既没有实现预加载,也没有实现延迟加载.但是我该如何检索/分配通过外键引用的任何对象?

I understand the EF7 has neither implemented eager-loading nor lazy-loading yet. But how would I then retrieve/assign any objects referenced via foreign key?

推荐答案

EF 7已实现了预加载.

EF 7 has implemented eager loading.

使用.include

Use .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

有关使用集合的更多信息,请参见以下问题的答案:如何使用集合

For more information on working with collections, see the answer to this question: How to work with collections

更多推荐

在EF7中加载参考

本文发布于:2023-11-15 14:24:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1595226.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:加载

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!