Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Core Find breaks with Nullable Id

Using EF Core 1.1 and Asp Core 1.1 on Mac

With a model like

public class Model {
  public int? Id { get; set; }
  public string OtherProp { get; set; }
}

And an action

public class ModelController
{
    public Model Get(int? id) 
    {
      DbContext.Set<Model>.Find(id)
    }
}

Accessing the url /model/10 fails with a message The key value at position 0 of the call to 'DbSet<Model>.Find' was of type 'int', which does not match the property type of 'Nullable<int>'

The error message is clear but my question is if there is a way to make this work, it seems like a very common use case and one that used to work in previous versions.

I tried casting id to int? but it didn't work. Any ideas?

Also, in case it's useful this is the line that's breaking in EF

like image 931
jorgehmv Avatar asked Jan 20 '26 18:01

jorgehmv


1 Answers

Looking at the code you've already linked: this cannot work, since the CLR gives you always the underlying type for a null-able instance. (Don't know why, had similar issues before...)

In code: typeof(int?) != ((int?)1).GetType().

Thus, comparing the type of the property (int?) and the type of the argument will always fail. You have to ask the EF Core team to add support for null-able types for that.

Related: Nullable type is not a nullable type?

like image 143
Axel Heer Avatar answered Jan 23 '26 04:01

Axel Heer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!