2015-09-28 55 views
-1

我有執行時拋出此異常的「查找」方法: 調用的目標引發異常。 ---> System.InvalidOperationException:類'NWatch.Entities.NWatchConvertMethod'沒有無參數的構造函數。實體框架 - 實體查找拋出無參數構造函數

將ConvertMethod添加到dbContext並保存更改沒有問題。

代碼:

[TestMethod] 
     public void Delete() 
     { 
      // Add the entry 
      var convertMethod = RenderConvertMethod(); 
      dbContext.ConvertMethods.Add(convertMethod); 
      dbContext.SaveChanges(); 
      int id = convertMethod.ConvertMethodId; 

      // Remove entry 
      dbContext.ConvertMethods.Remove(convertMethod); 
      dbContext.SaveChanges(); 

      // Ensure the entry no longer exists in the DB 
      // BELOW LINES THROWS THE EXCEPTION 
      var convertMethodFromDb = dbContext.ConvertMethods.Find(id); 
      Assert.IsNull(convertMethodFromDb); 
     } 

     private NWatchConvertMethod RenderConvertMethod() 
     { 
      var convertMethod = new NWatchConvertMethod("TestConvertMethod") 
      { 
       ConvertMethodDesc = "my description" 
      }; 

      return convertMethod; 
     } 
+2

好,有意義吧?你要求EF給你一個基於ID的對象。如果該對象需要構造參數,那麼EF將不知道如何構建它。給這個類一個無參數的構造函數。 – Jonesopolis

+0

所以爲了EF能夠使用基於它的PK來找到一個實體,它必須有一個無參數的構造函數?我從NWatchConvertMethod實體中取出構造函數,因爲「Name」是必需的。 – blgrnboy

回答

相關問題