3

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

jorgehmv
  • 3,633
  • 3
  • 25
  • 39
  • Why do you have a private setter (how could the value be set)? –  Feb 03 '17 at 04:58
  • I'm pretty sure that works with EF setting the value, but anyway, I tried making it public and got the same error. – jorgehmv Feb 03 '17 at 05:01
  • It was more related to how you would ever be able to bind the model when you submitted a form - it needs to be `public` –  Feb 03 '17 at 05:02
  • Gotcha, this is an oversimplified example just to focus on the error so I'll edit the setter so that it doesn't make more noise – jorgehmv Feb 03 '17 at 05:04
  • how id can be nullable? – Alexan Feb 03 '17 at 05:10
  • is that a "nullable" primary key? Can primary key be nullable? – Developer Feb 03 '17 at 05:13
  • For new instances it can be null, previous versions of EF allowed this. It's a small difference to check `Id.HasValue` vs `Id != 0`. I realize making it `int` would work but it'd be nice to keep it as `int?` – jorgehmv Feb 03 '17 at 05:16
  • @jorgehmv - my doubt was whether database supports null for primary key? – Developer Feb 03 '17 at 08:09

1 Answers1

2

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?

Community
  • 1
  • 1
Axel Heer
  • 1,863
  • 16
  • 22