我在EF 6中使用相同的方法并且工作正常,但使用EF核心v1.1.1的方法是抛出这样的异常。请看一下。
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;
}
}
答案 0 :(得分:2)
使用索引器获取属性值而不使用强制转换:
var current = entry.CurrentValues[property.Name];
应从foreach循环中排除主键属性。类似的东西:
if (property.Name == "Id") continue;
应该有效。否则你会得到
InvalidOperationException
:
'实体类型'Foo'上的属性'Id'是键的一部分,所以 不能修改或标记为修改。'