I trying to find the best way to update only specific fields using EF core. the problem is that there are many fields and marking each one of them as modified and changing its value makes the code very long and complicated.
is there a way to at least set the new value and mark as modified at one command?
this is how my code looks like now:
context.Entry(obj).Property("name").IsModified = true;
obj.name="Dan";
and it goes on and on for each field(about 30 fields, but the table is much larger).
I also tried this:
context.Entry(obj).Property("name").CurrentValue="Dan";
context.SaveChangesAsync();
but it doesn't update any records.
any help would be appreciated!
CodePudding user response:
Once you've fetched an object from the DB, simply update the properties' values and call SaveChanges
. EF will generate a query that updates only the properties with new values.
var myObj = await this.context.FindAsync(id);
myObj.Property1 = 42;
myObj.Property2 = "new value";
...
await this.context.SaveChangesAsync();
P.S. Make sure change tracking is enabled.
CodePudding user response:
I am usually using this algorithm
var existingObj = await Context.Set<obj>().FindAsync(id);//or use FirstOrDefault()
if (existingObj== null) return ...error;
existingObj.Name="name"
Context.Entry(existingObj).Property(i=>i.Name).IsModified = true;
Context.SaveChanges();