Ho lo stesso metodo in EF 6 e sto lavorando bene, ma l'uso del core EF v1.1.1 è il metodo che lancia un'eccezione come questa. Per favore dai un'occhiata.
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;
}
}
Usa l'indicizzatore per ottenere il valore della proprietà senza cast:
var current = entry.CurrentValues[property.Name];
La proprietà della chiave primaria deve essere esclusa dal ciclo foreach. Qualcosa di simile a:
if (property.Name == "Id") continue;
Dovrebbe funzionare. Altrimenti riceverai InvalidOperationException
:
'La proprietà' Id 'sul tipo di entità' Pippo 'fa parte di una chiave e quindi non può essere modificata o contrassegnata come modificata.'