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

时间:2015-01-08 15:27:39

标签: c# .net linq async-await entity-framework-6

我想在继续做其他事情之前等待此查询。我已经看到了关于这个主题的几个问题,但没有一个在查询中使用自定义函数,这使得它有点棘手。甚至可以使用等待以下查询。我使用Microsoft Async包在.NET4.0中使用await-async。(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 "";
        }

2 个答案:

答案 0 :(得分:4)

您可以使用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();

答案 1 :(得分:2)

如果在将查询的第一部分带入内存之前调用查询的第一部分,则await可以使用ToListAsync()代替ToList()

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