Entity Framework: Insert foreign key rows when Update table

c# entity-framework-6 repository-pattern

Question

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?

1
4
4/28/2019 8:50:11 PM

Popular Answer

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

0
4/29/2019 9:39:45 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow