ASP.NET Core for Beginners

FindAsync not working – … doesn’t match the property type of int

One of errors you can get in case of improperly used FindAsync() function is:

System.ArgumentException: The key value at position 0 of the call to ‘DbSet<Product>.Find’ was of type ‘Guid’, which does not match the property type of ‘int’.

The scenario where FindAsync may not work is for instance if you try to use it for field different than primary key. As it is, it looks for integers located in primary key column. 

Code which can trigger the above error message may look like below:

var product = await _dataContext.Products.FindAsync(productGuid)

And it would work, the problem is however, that productGuid is unique, but not primary key integer. To fix it, you need to replace FindAsync() function with FirstOrDefaultAsync(), assuming your column is productGUID:

var product = await _dataContext.Products.FirstOrDefaultAsync(p => p.productGUID == productGuid);