在 EF7 中加载引用

编程入门 行业动态 更新时间:2024-10-15 14:13:02
本文介绍了在 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属性为空.此外,当检索任何 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:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1595232.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:加载

发布评论

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

>www.elefans.com

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