![](/img/trans.png)
[英]The 'await' operator can only be used within an async lambda expression error
[英]The 'await' operator can only be used within an async lambda expression. Consider marking this lambda expression with the 'async' modifier
在以下 LinQ 查询中获取电话号码我正在调用另一个异步方法GetAspNetUserPhoneNumberByAccountId
,这会引发此错误
错误 CS4034 'await' 运算符只能在异步 lambda 表达式中使用。 考虑使用 'async' 修饰符标记这个 lambda 表达式。
任何人都知道吗?
var fullAppointment = await Task.Run(() => Context.AppointmentDetail
.Where(u =>
u.StartDateTime >= startdatetime
&& u.EndDateTime <= enddatetime
)
.Select(x => new Contracts.CalenderModel2()
{
StatusId = (Contracts.Enum.EnumWOStatus)x.Status,
FName = x.Appointment != null ? x.Appointment.Customer.Account.FName : "",
LName = x.Appointment != null ? x.Appointment.Customer.Account.LName : "",
**PrimaryPhone = x.Appointment != null ?
(await _userRepository.GetAspNetUserPhoneNumberByAccountId( x.Appointment.Customer.AccountId))**
: "",
Year = x.Appointment != null && x.Appointment.Vehicle != null ? x.Appointment.Vehicle.MakeYear.Year : 0,
Make = x.Appointment != null && x.Appointment.Vehicle != null ? x.Appointment.Vehicle.VehicleMaker.MakerName : "",
Model = x.Appointment != null && x.Appointment.Vehicle != null ? x.Appointment.Vehicle.VehicleModel.Model : "",
AppointmentId = x.AppointmentId,
JobEndDateTime = x.EndDateTime,
JobStartDateTime = x.StartDateTime,
ColorCategory = x.AppointmentType.ColorCategory,
SalesRepersentativeUserId =
(x.Appointment != null && x.Appointment.Customer.CustomerBillTo.Count > 0)
? x.Appointment.Customer.CustomerBillTo.FirstOrDefault().BillToId : Guid.Empty,
FullAppointmentDetail = new Contracts.FullAppointmentDetail
{
BayId = x.BayId,
BayName = x.WorkArea != null ? x.WorkArea.BayName : "",
WorkTypeId = x.WorkTypeId,
WorkTypeName = x.WorkType != null ? x.WorkType.WorkTypeName : "",
JobId = x.Appointment != null && x.Appointment.Job != null ? x.Appointment.Job.Id : Guid.Empty,
JobIdInt = x.Appointment != null && x.Appointment.Job != null ? x.Appointment.Job.JobIdInt : 0,
AssigneeUserId = x.AssigneeUserId,
WorkOrderId = x.WorkOrders.FirstOrDefault() != null ? x.WorkOrders.FirstOrDefault().Id : Guid.Empty
}
})
.ToList());
GetAspNetUserPhoneNumberByAccountId 的定义如下
public async Task<string> GetAspNetUserPhoneNumberByAccountId(Guid accountId)
{
var phone = await Task.Run(() => _Context.Account.Where(ac => ac.Id.Equals(accountId))
.Join(_Context.AspNetUsers, ac => ac.AspNetUserId, u => u.Id, (ac, u) => new
{
PhoneNumber = u.PhoneNumber,
}).FirstOrDefault());
return phone!=null?phone.ToString():"";
}
我同意评论中的人的意见,即您不需要在此查询中使用异步方法。 此外,此查询不会优化。 对于 Where 条件中的每个项目,您将对 DB 进行查询。 如果你有很多数据,DB 的性能就会下降。 我认为在这种情况下,最好对 DB 进行 2 次查询。 用于获取AppointmentDetail
和另一个用于获取所有帐户的查询。 并且两个查询都使用异步调用。 然后将其与您的Contracts.CalenderModel2
类结合起来。
它将更具可读性并更快地工作。 并且不要使用 Task.Run();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.