Entity Framework - lazy loading or optional async / wait request method?

I have these domain models

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; } } 

For example, I would like to implement the TestAsync method, where I want to work with the Topic object and related Posts objects.

Theme Model I can use the async method and topicId as a parameter.

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

And I have two ways how to get related messages. But what is the difference if I use LazyLoading or just another asynchronous request?

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

So, I think an example: 1 will work synchronously, and also I will lose all the benefits of async / wait code. But an example: 2 makes me think, maybe I don’t know all the charms of Lazy Loading :) Can someone clarify which solution I should use and why? Thanks:)

+5
source share
2 answers

Lazy loading is always synchronous, which is unfortunate. EF Core, for example, with its asynchronous mentality, does not yet support lazy loading.

Other options are to either make a connection (impatient download), as suggested by Peter, who asynchronously executes one request; or execute an explicit second asynchronous request. Which one you have chosen comes down to how your model is commonly used.

Personally, I would like to do the download with impatience if the models are always used together and otherwise execute several asynchronous requests. I do not use lazy loading on my own, although nothing would prevent it from working.

+6
source

You must not do this. I assume your GetByIdAsync () is implemented as follows.

 public async Task<Topic> GetByIdAsync(int id) { return await context.Topics.FirstAsync(t=>t.Id == id); } 

You have to change it like

 public async Task<Topic> GetByIdAsync(int id) { return await context.Topics.Include(t=>t.Posts).FirstAsync(t=>t.Id == id); } 
-1
source

Source: https://habr.com/ru/post/1270398/


All Articles