Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
2 of 21 tasks
Sufiane opened this issue May 10, 2021 · 22 comments
Closed
2 of 21 tasks

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

Sufiane opened this issue May 10, 2021 · 22 comments

Comments

@Sufiane
Copy link

Sufiane commented May 10, 2021

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 typescript@4.2.4
TypeORM version typeorm@0.2.32

Additional Context

using nest.js:
@nestjs/cli@7.6.0
typescript@4.2.3

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 !

@ganshiqingyuan
Copy link

seems like not set primaryColumns in entity

@Sufiane
Copy link
Author

Sufiane commented May 28, 2021

seems like not set primaryColumns in entity

it is set, that was the strangest part

@binvb
Copy link

binvb commented May 31, 2021

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

@imnotjames
Copy link
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.

@SFantasy
Copy link

@Sufiane it this problem solved ?

@Sufiane
Copy link
Author

Sufiane commented Jun 25, 2021

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

@Sufiane Sufiane closed this as completed Jun 25, 2021
@danieloi
Copy link

danieloi commented Sep 2, 2021

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

@Sufiane
Copy link
Author

Sufiane commented Sep 2, 2021

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 ?

@danieloi
Copy link

danieloi commented Sep 2, 2021

I'm not.

Thanks for responding

@danieloi
Copy link

danieloi commented Sep 2, 2021

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

@erald14
Copy link

erald14 commented Sep 3, 2021

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

@dehy
Copy link
Contributor

dehy commented Nov 29, 2021

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?

@davidarias
Copy link

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.

@jiayisheji
Copy link

I don't know why?

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

@ntedgi
Copy link

ntedgi commented Apr 3, 2022

@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.

@jiayisheji
Copy link

@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.

@dehy
Copy link
Contributor

dehy commented Apr 7, 2022

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!

@TranBaVinhSon
Copy link

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)

@Saintiano
Copy link

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

@ktamas77
Copy link

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.

@nhusby
Copy link

nhusby commented Aug 30, 2023

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().

@ricardocosta43
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests