SQL Server Temporary value error on SaveChanges in EF Core

hpxqektj  于 2023-06-21  发布在  其他
关注(0)|答案(1)|浏览(152)

When adding values to a table in EF Core I get the following error
The property ... has a temporary value while attempting to change the entity's state to 'Unchanged'. Either set a permanent value explicitly, or ensure that the database is configured to generate values for this property.

What is the code doing?

Imagine you have a table of data with multiple columns and you are attempting to store that table of data (think CSV, xslx etc) in a normalised form in a database. Some of the facets (columns) have their values already stored in the database, some need to be added, and some need to be updated.

A loose idea of the format of the source is...

Name, Facet1, Facet2, Facet2_1, Facet2_2, Numeric1, Numeric2

Where we will end up in the database with

Id, Name, Facet1_Id, Facet2_Id, Numeric1, Numeric2
Id, Facet1
Id, Facet2, Facet2_1_Id, Facet2_2_Id
Id, Facet2_1
Id, Facet2_2

The facet tables can be extended and the facet2 table can also be updated as the additional fields change from time to time. Facet2 table is system versioned.

Workflow

  • Load the file data
  • begin transaction
  • Fetch/extend facet1 data
  • Fetch/extend/update facet2 data
  • Map facets/ids (doesn't matter which way) to main data
  • Save changes.
  • end transaction

It is on the DbContext.SaveChanges() that the error occurs. If I perform a dirty read on the database (query with (nolock)) I see that every row of data I have processed is stored, which is not what I'd expect. I would expect at least one value to be missing to generate the issue. This seems like it succeeded but had some kind of internal EF issue.

The main data entity is setup with Id field as DatabaseGenerated(DatabaseGeneratedOption).Identity as are the Id fields for the other tables.

I have also tried with or without builder.Property(p => p.Id).ValueGeneratedOnAdd(); but still get the issue.

I have a different project in the solution that performs a similar task except the foreign keys do not go as many levels deep i.e. here I have

Main entity
   |         |
Facet1     Facet2
           |     |
       Facet2_1 Facet2_2

whereas the other project extends only one level in its processing/linking.

  • EF Core 7.0.0
  • SQL Server 2019
  • .NET 6.0
hrysbysz

hrysbysz1#

This seems to have been fixed by updating EF Core from 7.0.0 to 7.0.5

相关问题