I recently converted my code to more LINQ based code. But ReSharper warns me that the FindAsync function may return null. I don't want to check for null as I'm a bit obsessed with order. Does not checking for null cause problems in the future?
One of the old methods:
public async Task<IList<Post>> GetPostsByTagIdAsync(int tagId)
{
var posts = new List<Post>();
var postIds = context.PostsTags
.Where(pt => pt.TagId == tagId)
.Select(p => p.PostId);
foreach (var id in postIds)
posts.Add(await context.Posts.FindAsync(id));
return posts;
}
New version:
public async Task<IList<Post>> GetPostsByTagIdAsync(int tagId) =>
await context.PostsTags
.Where(pt => pt.TagId == tagId)
.Select(p => context.Posts.FindAsync(p.PostId).Result)
.ToListAsync();
CodePudding user response:
Both versions are ineffective. Better to ask for Posts in one database roundtrip.
public Task<IList<Post>> GetPostsByTagIdAsync(int tagId)
{
var query =
from pt in context.PostsTags
join p in context.Posts on pt.PostId equals p.Id
where pt.TagId == tagId
select p;
return query.ToListAsync();
}
Also query can be simplified if you have right navigation properties
public Task<IList<Post>> GetPostsByTagIdAsync(int tagId) =>
context.PostsTags
.Where(pt => pt.TagId == tagId)
.Select(pt => pt.Post)
.ToListAsync();
Note that, I have removed async
- it will also speedup execution, because compiler do not create additional state machine for handling asynchronous operations.