I have been working with ASP.NET Core to build the API and for data access I am using EF Core. Surfing around Stackoverflow and Google, I can't find a way to update only modified columns with the repository pattern.
Is there any way to check whether values have changed or not?
public virtual void Update(T entity)
{
// DbContext.Attach(entity);
var dbEntityEntry = DbContext.Entry(entity);
foreach (var property in dbEntityEntry.Properties)
{
var original = dbEntityEntry.OriginalValues.GetValue<object>(property.Metadata.Name);
var current = dbEntityEntry.CurrentValues.GetValue<object>(property.Metadata.Name);
if (original != null && !original.Equals(current))
dbEntityEntry.Property(property.Metadata.Name).IsModified = true;
}
}
I tried to implement like EF 6 but it is throwing an InvalidCastException
System.InvalidCastException: 'Unable to cast object of type System.Func'2[Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry,System.Int32]' to type 'System.Func`2[Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry,System.Object]'.'
I am directly updating object as received from client to in action controller and updating it.
Any help would be really appreciated.
Thanks