I have a generic save method that adds a TModel to a TDbSet and then does a SaveChanges().
To determine if this was an "add" or an "update" I was simply setting the entity state based on whether or not Id == 0, which was working as desired when the ids were all ints.
I then went through and modified the ids so they could be more generic as well, essentially allowing primary keys in my system to be either ints or guids as desired.
I haven't been able to figure out a solid test for determining if this is a save or modify in this scenario. I get the following error:
The property 'MyModel.Id' has a temporary value while attempting to change the entity's state to 'Modified'. Either set a permanent value explicitly, or ensure that the database is configured to generate values for this property.'
Which indicates that my condition is failing.
public virtual TModel Save(TModel data)
{
_dynamic.Add(data);
_context.Entry(data).State =
data.Id == null || (data?.Id.Equals(0) ?? true)
? EntityState.Added
: EntityState.Modified;
_context.SaveChanges();
return data;
}
Where Id is IEquatable<TKey>, in my particular scenario a long.
VS2022 is making it even more confusing by providing a value of 0 for data.Id in a watch, but then also providing a Expression has been evaluated and has no value in the tooltip when hovering over data?.Id.
I was hoping there was a clear-cut way to determine if the primary key for an entity was a "temporary value". I would think there must be, as this error message would have to know, but I haven't been able to unearth it. So far I can only find instances of people trying to find a way to set that value manually.