实体框架-延迟加载还是其他异步/等待查询方法? [英] Entity Framework - lazy loading or additional async/await query method?

查看:85
本文介绍了实体框架-延迟加载还是其他异步/等待查询方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这些域模型

public class Topic
{
    public int TopicId { get; set; }

    public virtual ICollection<Post> Posts { get; set; }
}

public class Post
{
    public int PostId { get; set; }

    public int? TopicId { get; set; }
    public virtual Topic Topic { get; set; }
}

例如,我想使用方法TestAsync,在那里我要使用Topic对象和相关的Posts对象.

For example I would like to impliment method TestAsync, there I want to work with Topic object and related Posts objects.

我可以使用异步方法和topicId作为参数来获得主题模型.

Topic model I can get using async method and topicId as param.

public async Task<bool> TestAsync(int topicId)
{
    var topic = await topicService.GetByIdAsync(topicId);

    // posts ...
}

我有两种方法,如何获取相关帖子. 但是,如果我将使用LazyLoading或仅使用另一个异步查询有什么区别?

And I have two ways, how to get related posts. But, what the difference if I will use LazyLoading or just another async query?

// Example: 1 (LazyLoading)
var posts = topic.Posts;

// OR Example: 2 (Async method)
var posts = await postService.GetAllByTopicIdAsync(topicId);

因此,我认为Example:1将同步工作,并且我失去了异步/等待代码的所有优点. 但是示例:2让我觉得,这可能是我不知道惰性加载的所有魅力:) 谁能澄清我应该使用哪种解决方案,为什么?谢谢:)

So, I think that Example:1 will works synchronously, and also that I lose all the advantages of async/await code. But Example: 2 makes me think, that may be I dont know all charms of Lazy Loading:) Could anyone clarify what solution I should use and why? Thanks:)

推荐答案

惰性加载始终是同步的,这是不幸的.例如,EF Core具有异步优先的思想,目前还不支持延迟加载.

Lazy loading is always synchronous, which is unfortunate. EF Core, for example, with its async-first mentality, does not (yet) support lazy loading.

其他选项是按照Peter的建议进行联接(快速加载),该联接异步执行单个查询.或执行显式的第二次异步查询.您会选择哪种模式取决于您通常使用模型的方式.

Other options are to either do a join (eager loading) as Peter suggested, which asynchronously performs a single query; or to do an explicit second asynchronous query. Which one you'd choose comes down to how your model is normally used.

就个人而言,如果模型始终一起使用,我会选择进行紧急加载,否则,将执行多个异步查询.我没有使用延迟加载自己,尽管没有什么可以阻止它工作.

Personally, I would choose to do the eager loading if the models are always used together, and do multiple asynchronous queries otherwise. I do not use lazy loading myself, though nothing would prevent it from working.

这篇关于实体框架-延迟加载还是其他异步/等待查询方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆