I have the same method in EF 6 and working just fine, but using EF core v1.1.1 is with method throwing an exception like this. Please take a look.
public virtual T Update(T obj)
{
try
{
if (null == obj) throw new ArgumentNullException(nameof(obj));
_context.Set<T>().Attach(obj);
var entry = _context.Entry(obj);
foreach (var property in entry.OriginalValues.Properties)
{
var current = entry.CurrentValues.GetValue<object>(property.Name); // <-- error occurring this line. If i set the generic type to specific like int,string etc the code work for the specific type only but if i set to object won't work.
entry.Property(property.Name).IsModified = current != null;
}
_context.SaveChanges();
//Detached the current context to get changes value
_context.Entry(obj).State = EntityState.Detached;
return obj;
}
catch (Exception ex)
{
Console.Write(ex);
throw;
}
}
Use indexer to get property value without cast:
var current = entry.CurrentValues[property.Name];
Primary key property should be excluded from foreach loop. Something like:
if (property.Name == "Id") continue;
Should work. Otherwise you'll get
InvalidOperationException
:
'The property 'Id' on entity type 'Foo' is part of a key and so cannot be modified or marked as modified.'