0

I have an entity with its primary key made up from two columns.

This is the model class:

public class DemoEntity
{
     public Guid EntityId {get;set;} // randomly generated primary key 

     public int Id {get;set;}. //auto increment identity primary key
 
     public string Description {get;set;}
}

I want to update couple of entities which I will be receiving from client. Client doesn't get EntityId, so in payload we won't have it.

Payload will look like this:

[
 {
   "id": 1,
   "description": "Updating entity with I'd =1"
 }
]

Above payload can have maximum 6 object.

In order to update the database, I am using this code:

[HttpPut]
public Task<ActionResult> Update([FromBody] List<DemoEntity> entities)
{
    _dbContext.UpdateRange(entities);
    await _dbContext.SaveChangesAsync();
    return No content();
}

This code is throwing an error while saving changes to the database:

An error occurred while saving the entity changes. See the inner exception for details.
Cannot insert non-DEFAULT value into column "id".
Column "id" is an identity column defined as GENERATED ALWAYS.

This error is getting fixed if I set EntityId. But we don't want to expose the EntityId to the client.

Is there any way to specify that which primary key EF core should use internally while updating the entity in case there are multiple primary keys are present?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • Do you mean alternate, composite, or candidate keys? https://stackoverflow.com/questions/217945/can-i-have-multiple-primary-keys-in-a-single-table – Kevin Krumwiede Oct 06 '22 at 04:54
  • Yes, I meant by composite key. – Mahendra Choudhary Oct 06 '22 at 04:58
  • It's **ONE** primary key (a relational entity - by definition - can *NEVER* have more than 1!), but it's made up from two columns. – marc_s Oct 06 '22 at 05:01
  • But why do you even think you need **two columns** in your primary key? `Id` on its own is already unique, non-null - this column alone would be perfect as your primary key. What's the intended benefit of adding this `EntityId` to your PK ?? Can't you just have the `EntityId` as a separate column, possibly with an unique constraint on it? – marc_s Oct 06 '22 at 05:38
  • We are moving to New data model where we are supposed to use IDs in GUID because our software has multiple databases/tables and we want IDs unique in each DB and table. Regarding integer ID it's migrated from our old database, as old Database was using int IDs. We want these IDs as it's being used in URLs, so we don't want to break old URLs. – Mahendra Choudhary Oct 06 '22 at 05:58

0 Answers0