2016-12-25 227 views
0

我是新来使用await /异步,我有一个基本的问题。我能够在我的WebApi控制器和业务对象(BL)中成功实现await/async模型以删除,因此我在Delete方法中调用了await entities.SaveChangesAsync();,并更新了方法的签名以返回public static async Task<ProfileItem> Delete(int profileId, int profileItemId),并且这个工作正常!当我“获取”数据时,我想要做同样的事情,所以,我有一个“getter”,我更新了方法的签名到public static async Task<List<Property>> GetProperties(int userId, int userTypeId),这里我有一些逻辑(1)使用实体框架来检索结果集,然后我做一些东西,并将我的EntityObject转换为BusinessObject并返回List<Property>,但是当我做return await ...时出现错误:列表不包含'GetAwaiter'的定义并且没有扩展方法...C#GetAwaiter异步任务<T>

下面的代码

public static async Task<List<Property>> GetProperties(int userId, int userTypeId) 
    { 

     entities = new MyEntities(); 

     var userType = entities.sl_USER_TYPE.Where(_userType => _userType.ID == userTypeId).First(); 


     var properties = entities.sl_PROPERTY.Where(_property => _property.USER_ID == userId && _property.USER_TYPE_ID == userTypeId); 

     if (!properties.Any()) 
      throw new Exception("Error: No Properties exist for this user!"); 

     // here is where I get the error 
     return await ConvertEntiesToBusinessObj(properties.ToList(), userId); 

    } 

什么我需要做的是能够访问是在这种情况下,这个功能的功能。基本上我可以使用任务/异步将信息保存到数据库但没有得到。我相信这是我缺乏理解。

感谢。

+2

的问题是'ConvertEntiesToBusinessObj'请显示该方法的代码 – CodingYoshi

+3

'VAR列表=等待properties.ToListAsync();。如果(list.Count == 0){抛出新的Exception(“Error:No Properties exists for this user!”);} else {return ConvertEntiesToBusinessObj(list,userId);}'如果你要检索元素,那么不需要单独执行'Any另外,你可以使用'等待FirstAsync()'而不是'First()'。 – PetSerAl

回答

3

您只能在“awaitables”上使用await,其中大部分意思是TaskTask<T>

ConvertEntiesToBusinessObj不返回Task<T>,这很好。这听起来像一个同步方法,所以它不应该。

你想要做的是使用ToListAsync代替ToList,并await认为:

return ConvertEntiesToBusinessObj(await properties.ToListAsync(), userId); 

此外,作为PetSerAI指出,这将是更有效地使用ToListAsync一次,而不是Any其次ToList/ToListAsync

public static async Task<List<Property>> GetProperties(int userId, int userTypeId) 
{ 
    entities = new MyEntities(); 
    var userType = await entities.sl_USER_TYPE.Where(_userType => _userType.ID == userTypeId).FirstAsync(); 
    var properties = await entities.sl_PROPERTY.Where(_property => _property.USER_ID == userId && _property.USER_TYPE_ID == userTypeId).ToListAsync(); 

    if (!properties.Any()) 
    throw new Exception("Error: No Properties exist for this user!"); 

    return ConvertEntiesToBusinessObj(properties, userId); 
} 

的一般规则在这里遵循的是方法async以“我想让这个功能异步; “这种合适的方法是首先识别自然异步操作(通常是基于I/O的操作) - 在本例中为EF查询,然后使异步并用await调用它们,并允许async/await从那里自然生长