EF Core property type exception


I ran into an entity framework issue where I received the following exception on an update controller method. I was attempting to use the Find and/or FindAsync methods on a DbSet to locate a single record by it's key value. The problem was that I passed the wrong type into Find. With an int key table Find expects that an int be passed but instead I passed it an object with an int property which it correctly complained about being an anonymous type of int.

C#

this.DbSet.FindAsync(new { id });

It should be noted, this exception will occur anytime there is a data type mismatch (e.g. if you have a string or guid key but pass an int, expect this error). There are scenarios where you can pass in an anonymous type but alas this was not one of them.

Exception

The key value at position 0 of the call to 'DbSet<T>.Find' was of type '<>f__AnonymousType0<int>', which does not match the property type of 'int'.

C#

// Correct
var record = await this.DbSet.FindAsync(id);
		
// Incorrent
var record = await this.DbSet.FindAsync(new { id });

Leave a comment

Please note that we won't show your email to others, or use it for sending unwanted emails. We will only use it to render your Gravatar image and to validate you as a real person.