[英]ASP.NET Core Web API - Cannot implicitly convert type 'System.Threading.Tasks.Task<Merchant?>' to 'Merchant'
In my ASP.NET Core-6 Web API, I am implementing Repository pattern.在我的 ASP.NET Core-6 Web API 中,我正在实现存储库模式。 I have this code:我有这个代码:
Model:模型:
public class Merchant
{
public Guid Id { get; set; }
[Required]
[Column(TypeName = "Varchar")]
[StringLength(100)]
public string MerchantName { get; set; }
[Required]
[Column(TypeName = "Varchar")]
[StringLength(50)]
public string AccountNumber { get; set; }
public NotificationRequired? NotificationRequired { get; set; }
public string NotificationUrl { get; set; }
}
Interface:界面:
public interface IAdminMerchantRepository : IGenericRepository<Merchant>
{
Merchant GetMerchantById(Guid id);
}
public class AdminMerchantRepository : GenericRepository<Merchant>, IAdminMerchantRepository
{
private readonly ApplicationDbContext _dbContext;
private readonly DbSet<Merchant> _adminMerchants;
public AdminMerchantRepository(ApplicationDbContext dbContext) : base(dbContext)
{
_dbContext = dbContext;
_adminMerchants = _dbContext.Set<Merchant>();
}
public Merchant GetMerchantById(Guid id)
{
var merchant = _dbContext.Merchants.Include(e => e.User)
.FirstOrDefaultAsync(e => e.Id == id);
return merchant;
}
}
I got this strange error:我收到了这个奇怪的错误:
Cannot implicitly convert type 'System.Threading.Tasks.Task<Merchant?>' to 'Merchant'无法将类型“System.Threading.Tasks.Task<Merchant?>”隐式转换为“Merchant”
It highlights merchant in return merchant它在回报商人中突出商人
I never used any Task.我从未使用过任何任务。
Where is it getting the error from, and how do I resolve it?它从哪里得到错误,我该如何解决?
Thank you.谢谢你。
You state "I never used any Task", but this is not true.您说“我从未使用过任何任务”,但事实并非如此。 The variable var merchant
has type System.Threading.Tasks.Task<Merchant?>
, because you use .FirstOrDefaultAsync(e => e.Id == id)
when creating it.变量var merchant
的类型为System.Threading.Tasks.Task<Merchant?>
,因为您在创建它时使用.FirstOrDefaultAsync(e => e.Id == id)
。 If you replace it with .FirstOrDefault(e => e.Id == id)
, you will be fine (except, of course, that it will return a Merchant?
instead of a Merchant
).如果你用.FirstOrDefault(e => e.Id == id)
替换它,你会没事的(当然,它会返回Merchant?
而不是Merchant
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.