2017-04-15 49 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

‘的實體類型「‘屬性’身份證富’是一個關鍵的組成部分,所以 不能被修改或標記爲修改。」