Reputation: 857
I would like to wait for this query before proceeding to do anything else. I have seen several question on this topic but none of those are using custom function in the query, which is making it little tricky. Is it even possible to use await with following query. I am using await-async in .NET4.0 using Microsoft Async package.(https://www.nuget.org/packages/Microsoft.Bcl.Async/)
var Employees =
(from d in context.Employees
join a in context.Address on d.ID equals a.EmployeeID
select new
{
Employee = d,
Address = a,
})
.AsEnumerable() memory
.Select(x => new Employee
{
Id = x.Employee.Id,
PreferredName = GetPreferredName(x.Employee.FirstName, x.Employee.MiddleName, x.Employee.LastName, x.Employee.Alias),
StreetAddress = x.Address.StreetAddress
})
.ToList();
private string GetPreferredName(string firstName, string middleName, string lastName, string dnsName)
{
if (!string.IsNullOrEmpty(firstName))
return firstName;
else if (!string.IsNullOrEmpty(middleName))
return middleName;
else if (!string.IsNullOrEmpty(lastName))
return lastName;
else if (!string.IsNullOrEmpty(dnsName))
return dnsName;
return "";
}
Upvotes: 2
Views: 211
Reputation: 203834
You can use ToListAsync
to asynchronously get the results of an EF query.
var query = await
(from d in context.Employees
join a in context.Address on d.ID equals a.EmployeeID
select new
{
Employee = d,
Address = a,
})
.ToListAsync();
var Employees = query
.Select(x => new Employee
{
Id = x.Employee.Id,
PreferredName = GetPreferredName(x.Employee.FirstName, x.Employee.MiddleName, x.Employee.LastName, x.Employee.Alias),
StreetAddress = x.Address.StreetAddress
})
.ToList();
Upvotes: 4
Reputation: 149538
You can await
using ToListAsync()
instead of ToList()
if you invoke your first part of the query before bringing it in to memory:
var queryEmployees = await
(from d in context.Employees
join a in context.Address on d.ID equals a.EmployeeID
select new
{
Employee = d,
Address = a,
}).ToListAsync();
var employees = Employees.Select(x => new Employee
{
Id = x.Employee.Id,
PreferredName = GetPreferredName(x.Employee.FirstName, x.Employee.MiddleName, x.Employee.LastName, x.Employee.Alias),
StreetAddress = x.Address.StreetAddress
})
.ToList();
Upvotes: 2