I have two entities, one is the one in the database the other is the new value i received from the controller.
Now i want to update the entity in the Database without specifying all the different properties;
Instead of:
public async Task UpdateFoo(Foo fooNew){
Foo fooDb = await context.Foo
.Include(f => f.Child)
.Where(f => f.Id == 1)
.FirstOrDefaultAsync();
fooDb.Value01 = fooNew.Value01;
fooDb.Value02 = fooNew.Value02;
fooDb.Child.ValueA = fooNew.Child.ValueA;
context.SaveChangesAsync()
}
I want to do something like;
public async Task UpdateFoo(Foo fooNew){
Foo fooDb = await context.Foo
.Include(f => f.Child)
.Where(f => f.Id == 1)
.FirstOrDefaultAsync();
fooDb = fooNew;
context.SaveChangesAsync()
}
I tried using CurrentValues.SetValues;
context.Entry(fooDb).CurrentValues.SetValues(fooNew);
This results in an error because of the key being marked as modified;
The property 'Id' on entity type 'Foo' is part of a key and so cannot be modified or marked as modified.
Is there a way to overwrite and save all entity properties (and entity child properties) without specifying them one by one?
How about you start by attaching the model to a DbSet<T>
then telling EF tracker to update all its fields whenever you call .SaveChanges()
Sample code looks like this.
public async Task UpdateFoo(Foo foo_updated)
{
foo_updated = context.Set<Foo>()
.Attach(foo_updated);
context.Entry(foo_updated).State = EntityState.Modified;
context.Entry(foo_updated.Child).State = EntityState.Modified;
context.SaveChangesAsync()
}