2017-04-15 57 views
1

我在EF 6中有相同的方法,并且工作得很好,但使用EF核心v1.1.1的方法是抛出一个像这样的异常。请看一下。 enter image description here无法投射EntityEntry当前值

 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; 
     } 
    } 

回答

1

使用索引来获得属性值,而投:

var current = entry.CurrentValues[property.Name]; 

主键属性应该从foreach循环中排除。例如:

if (property.Name == "Id") continue; 

应该工作。否则,你会得到 InvalidOperationException

‘的实体类型“‘属性’身份证富’是一个关键的组成部分,所以 不能被修改或标记为修改。”