I'm using EF Core 2.2.4.
This is my entity:
public class Person
{
public int? Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
}
Notice that Person
has a nullable-type primary key. This seems to be handled gracefully by EF Core and at the end entities get their Id; I used the term 'nullable-type' PK instead of 'nullable PK' because the intention is NOT to insert record with null PK, that is generated by the database, but to handle correctly the situation of entities for which the key has not yet been generated.
And as I said, generation seems to work fine. Not everything works nicely though.
AppDbContext dbc = new AppDbContext();
Person p1 = new Person() { Name = "Isaac", Surname = "Newton" };
dbc.Add(p1);
dbc.Remove(p1);
dbc.SaveChanges();
If I run this code, the line dbc.Remove(p1)
doesn't work properly in fact I get this error:
System.ArgumentNullException: 'Value cannot be null. Parameter name: key'
If I change the Id from int?
to int
, the above code works.
It seems that in case of nullable-type keys the temporary (negative) Id
doesn't get assigned to the Id.
Nullable-type keys have some advantages, mainly not showing the temporary Id that seems to be generated lazily, in the Save phase.
I couldn't find in the documentation if this is a supported feature and what I'm seeing is a bug or rather this is simply an unsupported feature and I should avoid nullable-type primary keys tout-court.