是否可以将 await 与使用自定义函数的查询一起使用

本文关键字:自定义函数 查询 一起 await 是否 | 更新日期: 2023-09-27 18:36:50

我想等待此查询,然后再继续执行其他任何操作。我已经看到了几个关于这个主题的问题,但没有一个在查询中使用自定义函数,这使得它有点棘手。是否可以将等待与以下查询一起使用。我在 中使用等待异步。使用Microsoft异步包的 NET4.0。(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 "";
        }

是否可以将 await 与使用自定义函数的查询一起使用

可以使用

ToListAsync异步获取 EF 查询的结果。

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();
如果在将

查询引入内存之前调用查询的第一部分,则可以使用 ToListAsync() 而不是ToList() await

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();