希望我能够清楚地解释我自己,因为我对async/await
和Task
的新手很熟悉。使用自定义DTO和实体框架进行异步编程
基本上我正在走自学异步编程的道路,尽管从根本上说,我完全理解了这个概念,以及何时最适用。
虽然在我的项目中,我可能已经有点过度。所以我一直都很喜欢制作自己的DTO,而且我并不喜欢使用第三方工具(AutoMapper)来做到这一点,但可能会带来很大的遗憾,因为我不确定如何从手动映射返回Task<DTO>
。
如果我可以详细说明:
客户回购
public sealed class ClientRepository : IClientRepository
{
private ClientConfigEntities _context;
public ClientRepository(ClientConfigEntities context)
{
_context = context;
}
public async Task<Client> AuthenticateAsync(string apiKey, string password)
{
//Throws error because it cannot return Task<Client> from Client
return await MapClient.ToModel(_context.tbl_Client
.FirstOrDefaultAsync(c => c.ApiKey == apiKey
&& c.Password == password));
}
}
映射
public static class MapClient
{
public static Client ToModel(tbl_Client source)
{
return (source != null) ? new Client
{
Id = source.Id,
ApiKey = source.ApiKey,
ApiURL = source.ApiURL,
ClientKey = source.ClientKey,
Password = source.Password,
RetainMeApiKey = source.RetainMeApiKey,
Secret = source.Secret
}
: null;
}
}
我也有另一个抽象AuthenticationService
然后将其称为一个Controller
- 让我隐藏复杂性。
以上我已经试过在static
映射方法上返回一个Task<Client>
,但我相信你知道,它会抛出类型问题。
什么是返回一个异步Task<Client>?
真希望有人可以给我深入了解如何以及为什么最好的方法?
大加赞赏,对什么FirstOrDefaultAsync
回报
感谢您的帮助,对于扩展方法提示+1。 –