4

By making use of Entity Framework 6 as well as a repository pattern, I'm trying to update a row, where the existing row has a new foreign key object associated with it. For example a Person record already exists. The Person get a new Dog. So now the Person class has a Dog property instantiated and populated with data.

This is my update method:

public async Task<TObject> UpdateAsync(TObject updated, int key)
{
    if (updated == null)
        return null;

    var existing = await this._context.Set<TObject>().FindAsync(key);
    if (existing != null)
    {
        this._context.Entry(existing).CurrentValues.SetValues(updated);
    }

    await this._context.SaveChangesAsync();

    return existing;
}

And I call it by doing the following:

personRecord.Dog = new Dog () { Name = "Max", Age = 7 };
await this.PersonRepository.UpdateAsync(personRecord, personRecord.Id)

But no new Dog record is being inserted into the database. What am I doing wrong?

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Richard Bailey
  • 2,658
  • 4
  • 27
  • 45

1 Answers1

0

did you check the state of entity person and entity dog ?

the entity state must be in modified state or created state before saveChange() to

perform the insert

you can check this statut with

context.Entry(person).State

Han solo
  • 44
  • 2