How to make Entity Framework Core to give added entity negative ID

c# ef-core-3.0 entity-framework-core

Question

I'm trying to get EF Core 3.0 to give me negative ID of newly added entity. As far as I know, EF Core have this functionality build in. But when calling Add on DbSet I'm keep getting 0, Is there any way to turn this function on?

1
1
4/10/2020 1:13:41 PM

Accepted Answer

This behavior was expected in 3.0?

Yes, it is one of the 3.0 Breaking Changes - Temporary key values are no longer set onto entity instances.

The proposed solutions there are:

  • Not using store-generated keys.
  • Setting navigation properties to form relationships instead of setting foreign key values.
  • Obtain the actual temporary key values from the entity's tracking information. For example, context.Entry(blog).Property(e => e.Id).CurrentValue will return the temporary value even though blog.Id itself hasn't been set.

Option #1 doesn't make sense (apparently the affected places already use store generated keys).

Option #2 is preferable if you have navigation properties.

Option #3 is closer to the previous behavior, but requires access to the db context.

2
9/28/2019 2:13:50 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow