Skip to content

Cannot update entity because entity id is not set in the entity. #7643

Closed

Description

@Sufiane

Issue Description

When trying to save a record I get Cannot update entity because entity id is not set in the entity.
The payload do not contain any id.

Expected Behavior

Being able to create a new record.

Actual Behavior

Throws the error 'Cannot update entity because entity id is not set in the entity.'

Steps to Reproduce

  1. Get a transaction,
  2. Run save method on your entity with said EntityManager and a payload without "id" property.
return this.repo.manager.transaction(entityManager) => {
     return entityManager.save(Entity, payload);
})

My Environment

Dependency Version
Operating System MacOs 11.2.3
Node.js version v14.16.1 and v12.18.4
Typescript version [email protected]
TypeORM version [email protected]

Additional Context

using nest.js:
@nestjs/[email protected]
[email protected]

Relevant Database Driver(s)

  • aurora-data-api
  • aurora-data-api-pg
  • better-sqlite3
  • cockroachdb
  • cordova
  • expo
  • mongodb
  • mysql
  • nativescript
  • oracle
  • postgres
  • react-native
  • sap
  • sqlite
  • sqlite-abstract
  • sqljs
  • sqlserver

Are you willing to resolve this issue by submitting a Pull Request?

  • Yes, I have the time, and I know how to start.
  • Yes, I have the time, but I don't know how to start. I would need guidance.
  • No, I don't have the time, although I believe I could do it if I had the time...
  • No, I don't have the time and I wouldn't even know how to start.

Thanks in advance for any help !

Activity

  1. ganshiqingyuan commented on May 28, 2021

    @ganshiqingyuan

    seems like not set primaryColumns in entity

  2. Sufiane commented on May 28, 2021

    @Sufiane
    Author

    seems like not set primaryColumns in entity

    it is set, that was the strangest part

  3. binvb commented on May 31, 2021

    @binvb

    same problem, if don't use default property, it's fine

  4. imnotjames commented on Jun 21, 2021

    @imnotjames
    Contributor

    When opening an issue, people will be better able to provide help if you provide code that they can easily understand and use to reproduce the problem. This boils down to ensuring your code that reproduces the problem follows the following guidelines:

    • Minimal – Use as little code as possible that still produces the same problem
    • Complete – Provide all parts someone else needs to reproduce your problem in the question itself
    • Reproducible – Test the code you're about to provide to make sure it reproduces the problem

    Minimal

    The more code there is to go through, the less likely people can find your problem. Streamline your example in one of two ways:

    1. Restart from scratch. Create a new program, adding in only what is needed to see the problem. Use simple, descriptive names for functions and variables – don’t copy the names you’re using in your existing code.
    2. Divide and conquer. If you’re not sure what the source of the problem is, start removing code a bit at a time until the problem disappears – then add the last part back.

    Don't sacrifice clarity for brevity when creating a minimal example. Use consistent naming and indentation, and include code comments if needed. Use your code editor’s shortcut for formatting code.

    Don't include any passwords or credentials that must be kept secret.

    Complete

    Make sure all information necessary to reproduce the problem is included in the issue itself.

    If the problem requires some code as well as some XML-based configuration, include code for both. The problem might not be in the code that you think it is in.

    Use individual code blocks for each file or snippet you include. Provide a description for the purpose of each block.

    DO NOT use images of code. Copy the actual text from your code editor, paste it into the issus, then format it as code. This helps others more easily read and test your code.

    Reproducible

    To help you solve your problem, others will need to verify that it exists.

    Describe the problem. "It doesn't work" isn't descriptive enough to help people understand your problem. Instead, tell other readers what the expected behavior should be. Tell other readers what the exact wording of the error message is, and which line of code is producing it. Use a brief but descriptive summary of your problem as the title of your question.

    Eliminate any issues that aren't relevant to the problem. If your question isn’t about a compiler error, ensure that there are no compile-time errors.

    Double-check that your example reproduces the problem! If you inadvertently fixed the problem while composing the example but didn't test it again, you'd want to know that before asking someone else to help.

  5. SFantasy commented on Jun 25, 2021

    @SFantasy

    @Sufiane it this problem solved ?

  6. Sufiane commented on Jun 25, 2021

    @Sufiane
    Author

    @SFantasy yeah it resolved itself, i guess we can close the issue

  7. danieloi commented on Sep 2, 2021

    @danieloi

    I still have the same issue. How did you resolve it @Sufiane?

  8. Sufiane commented on Sep 2, 2021

    @Sufiane
    Author

    I still have the same issue. How did you resolve it @Sufiane?

    to be honest it went by itself, i destroyed the dist multiple times restarted my app.

    Are you using class-transformer/validator maybe ?

  9. danieloi commented on Sep 2, 2021

    @danieloi

    I'm not.

    Thanks for responding

  10. danieloi commented on Sep 2, 2021

    @danieloi

    I found an answer in the thread here
    #4651

    You want to set the reload option in the argument to save's options argument to false

  11. erald14 commented on Sep 3, 2021

    @erald14

    For me it was because I wasn't using
    @PrimaryGeneratedColumn() in the entity definition

  12. dehy commented on Nov 29, 2021

    @dehy
    Contributor

    I found an answer in the thread here #4651

    You want to set the reload option in the argument to save's options argument to false

    Thanks for the info! But why should we have to set this option? On 0.2.34, it's working fine without this option, on 0.2.35+, I have to set it. What happened?

  13. davidarias commented on Dec 1, 2021

    @davidarias

    I have the same issue updating from 0.2.34 to latest ( 0.2.41 ).

    Saving using the reload flag to false fixed the problem, but as dehy says, I'm wondering why this change is needed.

  14. jiayisheji commented on Mar 29, 2022

    @jiayisheji

    I don't know why?

    I set primary key id = null before .save() and there is no error。

  15. ntedgi commented on Apr 3, 2022

    @ntedgi

    @jiayisheji check your sql mode

    NO_AUTO_VALUE_ON_ZERO affects handling of AUTO_INCREMENT columns. Normally, you generate the next sequence number for the column by inserting either NULL or 0 into it. NO_AUTO_VALUE_ON_ZERO suppresses this behavior for 0 so that only NULL generates the next sequence number.

  16. jiayisheji commented on Apr 4, 2022

    @jiayisheji

    @ntedgi Fix Typeorm bug not mysql error.

    https://github.com/typeorm/typeorm/blob/master/src/metadata/ColumnMetadata.ts#ColumnMetadata.getEntityValueMap() :

    if() {}
    else {
       if () {}
      else {
          // If not set null ,else undefined
          if (entity[this.propertyName] !== undefined && (returnNulls === false || entity[this.propertyName] !== null))
              return { [this.propertyName]: entity[this.propertyName] };
    
          return undefined;
      }
    }

    not set null insert:

    INSERT INTO `users`(`id`, `username`, `password`, `created_at`, `updated_at`) VALUES (DEFAULT, ?, ?, DEFAULT, DEFAULT) --PARAMETERS: ["jiayi", "123456"]

    mysql insert id = 0;

    set null insert:

    INSERT INTO `users`(`id`, `username`, `password`, `created_at`, `updated_at`) VALUES (null, ?, ?, DEFAULT, DEFAULT) --PARAMETERS: ["jiayi", "123456"]

    mysql insert id = 1++;

    I don't know why, I set null to fix Typeorm bugs and mysql insert issues.

  17. dehy commented on Apr 7, 2022

    @dehy
    Contributor

    I don't know why?

    I set primary key id = null before .save() and there is no error。

    entity.id = null before saving, you're the man 🚀 It works for me too.

    Still needs a proper fix!

  18. added a commit that references this issue on Apr 7, 2022
  19. TranBaVinhSon commented on May 7, 2022

    @TranBaVinhSon

    I set primary key id = null before .save() and there is no error。

    yeah but as @jiayisheji mentioned here, if I set id to null , the primary key (id) will be increased. Anyone have solutions for this ?

    #7643 (comment)

  20. Saintiano commented on Feb 11, 2023

    @Saintiano

    This is caused when the table primary key (id) does not have Auto Increment set or marked,
    In that case you will have to be inserting the primary key by yourself

  21. ktamas77 commented on Mar 19, 2023

    @ktamas77

    I don't know why?

    I set primary key id = null before .save() and there is no error。

    unfortunately this solution will keep generating new records on upsert, instead of updating the current one, when the constraint is not the primary key.

  22. nhusby commented on Aug 30, 2023

    @nhusby

    I was having this error on an entity with a compound primary key. In our case, the problem was that one of the properties was not being automatically filled.

        @PrimaryGeneratedColumn({ type: "int", name: "cdr_id", unsigned: true })
        cdrId: number;
        
        @PrimaryColumn("int", { name: "date", unsigned: true, nullable: false })
        date: number;
    

    The solution was to use our custom date decorator (we are using unix_timestamp integer values.)

        @CreateDate()
        @PrimaryColumn("int", { name: "date", unsigned: true, nullable: false })
        date: number;
    

    If you're getting this error, it's probably because your primary key, or part of your primary key is not being populated for whatever reason. You either need to provide a value in code, or use a default value the DB can fill in. In our case, unix_timestamp doesn't work as a default value so we use a @BeforeInsert() to fill in the date columns tagged with @Createdate().

  23. ricardocosta43 commented on Sep 9, 2023

    @ricardocosta43

    It's not my case, the key in the table was not auto-incrementing
    Captura de Tela 2023-09-09 às 05 57 52

  24. humayyun00 commented on Jul 18, 2024

    @humayyun00

    You have to set the generation strategy for your primary key when creating the table
    Like this
    ```
    name: "id",
    type: "integer",
    isPrimary: true,
    isGenerated:true,
    generationStrategy: 'increment'

  25. danielps-fideclub commented on Jan 9, 2025

    @danielps-fideclub

    i got the same issue and this was the answer after some testing. i added .updateEntity(false). I still dont have all teh details associated to this behaviour.
    https://stackoverflow.com/questions/74149526/typeorm-cannot-update-entity-because-entity-id-is-not-set-in-the-entity

                            .createQueryBuilder()
                            .insert()
                            .into(VendorAmenities)
                            .values({
                                referenceId: id,
                                referenceType: 'station',
                                amenities,
                            })
                            .orUpdate(['amenities'], ['reference_id'], { skipUpdateIfNoValuesChanged: true })
                            .updateEntity(false)
                            .execute();
                    }```
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions