在下面的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():"";
}
答案 0 :(得分:0)
我同意您在注释中不需要使用异步方法的意见。另外,该查询将不会优化。对于条件条件中的每个项目,您都将查询到数据库。如果您有大量数据,DB的性能将下降。我认为在这种情况下最好对数据库执行2次查询。用于获取AppointmentDetail
和用于获取所有帐户的另一个查询。并且两个查询都带有异步调用。然后将其组合到您的Contracts.CalenderModel2
类中。
它将更具可读性并且工作更快。 而且不要使用Task.Run();