How update entity after adding new entity in EF Core

You are using EF Core like when you write raw SQL queries, which kind of beats many of the advantages of an ORM.

You don't need the ClientId for ClientSecrets, because EF Core can figure out the relations itself.

var newClient = new Client
{
    ClientName = client.ClientName,
    ClientId = client.ClientId,
    ClientSecrets = secrets.ToList() // or ToArray or whatever it is
};

_dbContext.Clients.Add(newClient);
await _dbContext.SaveChangesAsync();

It's not a problem that ClientSecret requires a back reference to the Client class, by adding your secrets to the model, you establish a relationship of ClientSecret to Client.

When you save now, EF Core will know it has first to add the Client and then add the ClientSecrets


The instance of entity type 'Client' cannot be tracked because another instance of this type with the same key is already being tracked

there is already an instance of client created on _dbContext.Clients.Add(newClient);.

you need to Detach the first entry before attaching your updated entry

after

_dbContext.Clients.Add(newClient);
await _dbContext.SaveChangesAsync();

add code for detaching

_dbcontext.Entry(newClient).State = EntityState.Detached;