简体   繁体   中英

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. 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'

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. 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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM