【发布时间】:2020-06-04 05:22:32
【问题描述】:
在构建投票应用练习时,我正在使用 WebAPI 玩 EntityFrameworkCore。
我希望尽可能以异步方式编写代码。
那么我是否必须以某种方式以异步方式使用嵌套查询(// 问题 1,// 问题 2)?
/* The target of the question - the query*/
var pollResults =
await _context.Polls
.Select(poll => new PollDto
{
Id = poll.Id,
Question = poll.Question,
CreatedAt = poll.CreatedAt,
Options = poll.Options
.Select(option => new OptionDto
{
Id = option.Id,
Value = option.Value,
VotesCount = option.Votes.Count() // Problem 1
})
.ToList(), // Problem 2
LastVotedAt = _context.PollVotes.Where(vote=>vote.PollId == poll.Id).Select(vote => vote.VoteDate).SingleOrDefault()
})
.ToListAsync();
/* Domain classes */
public class Poll
{
public int Id { get; set; }
public ICollection<PollOption> Options { get; set; } = new List<PollOption>();
public ICollection<PollVote> Votes { get; set; } = new List<PollVote>();
}
public class PollOption
{
public int Id { get; set; }
public string Value { get; set; }
public int PollId { get; set; }
public Poll Poll { get; set; }
public ICollection<PollVote> Votes { get; set; } = new List<PollVote>();
}
public class PollVote
{
public int Id { get; set; }
public int PollId { get; set; }
public Poll Poll { get; set; }
public int OptionId { get; set; }
public PollOption Option { get; set; }
public DateTime VoteDate { get; set; }
}
/* Dto classes */
public class PollDto
{
public int Id { get; set; }
public string Question { get; set; }
public ICollection<OptionDto> Options { get; set; } = new List<OptionDto>();
public DateTime LastVotedAt { get; set; }
}
public class OptionDto
{
public int Id { get; set; }
public string Value { get; set; }
public int VotesCount { get; set; }
}
因此,在非嵌套查询中,Count 和 SingleOrDefault 会向数据库发出请求,并且应该以异步方式执行。但在我的情况下,整个查询是一个请求。
我应该修改一些东西以异步方式完成方法 Count 和 SingleOrDefault 吗?还是最后调用 ToListAsync 就够了?
我相信答案是对数据库的 1 个请求进入 1 个异步调用。但是我在互联网上没有找到任何解决方案。
【问题讨论】:
-
在玩了几个小时后,我意识到:1. 调用 Count(来自问题 1)告诉 EF 如何对数据库进行查询。因此不会获取所有选票,而只是添加在数据库级别的 PollVotes 表上工作的 VotesCount; 2. 在我的应用程序级别调用 ToList(来自问题 2)处理已收到的数据。所以我的两个问题是不同的。如果我错了,请修理我。
标签: c# asp.net sql-server entity-framework entity-framework-core