2013-08-26 54 views
1

這一直困擾着我過去的一個小時,我無法找出究竟發生了什麼問題。我試圖從我們的數據庫中檢索一個對象以及其他幾個對象(它們可以很好地返回)。我得到一個異常從數據庫中檢索對象問題

object of type 'system.string' cannot be converted to type 'system.int32' 

這是奇怪的,因爲只有兩個在這裏打球的變量,無一不是數據類型INT的。這是代碼。

控制器

public ActionResult EditGABuyContract(int id) 
    { 
     var p = PropertyService.GetPropertyBy(id); 
     if (p == null) 
      return RedirectToRoute(new { Controller = "Dashboard", Action = "Index" }); 
     var purchase = PropertyService.GetPropertyPurchaseBy(id); //This works just fine 
     var buyContract = PropertyService.GetGABuyContractById(id); //This leads to the exception 


... 

服務

public PropertyGABuyContract GetGABuyContractById(int propertyid) //This leads to an exception 
{ 
    try 
    { 
     return ((IRepositoryBase)PropertyRepository).GetByPropertyId<PropertyGABuyContract>(propertyid); 


    } 
    catch (Exception ex) 
    { 
     Log.Error(ex); 
     return null; 
    } 
} 

public PropertyPurchase GetPropertyPurchaseBy(int propertyid) //This does NOT lead to an exception 
{ 
    try 
    { 
     return ((IRepositoryBase) PropertyRepository).GetByPropertyId<PropertyPurchase>(propertyid); 


    } 
    catch (Exception ex) 
    { 
     Log.Error(ex); 
     return null; 
    } 
} 

public T GetByPropertyId<T>(int id) where T : PropertyBase, new() 
{ 
    return repo.Single<T>(t => t.PropertyId == id); //Exception occurs here for only GetGABuyContract() method and not for the GetPropertyPurchaseById() method 
} 

此異常不對我有意義。 PropertyPurchase和PropertyGABuyContract都從繼承PropertyId的相同PropertyBase類繼承。

回答

0

問題必須是PropertyId定義爲一種類型的int和另一種類型的string

如果是的話這應該工作:

t => int.Parse(t.PropertyId.ToString()) == id 

,或者你可以修改資料庫項目爲int。

+0

沒有。我試過t => int.Parse(t.PropertyId.ToString())== int.Prase(id.toString()),它仍然返回相同的錯誤。在SQL中,PropertyId被定義爲兩個表中的int,並且在PropertyBase類中定義爲int。在我正在嘗試給一個整數指定一個字符串的賦值過程中,應該不可能讓我傳入的變量或字段有一個字符串,而不會收到錯誤,因爲我明確聲明瞭它們全部。 –

0

我找到了問題的解決方案。我的其他同事之一改變了數據庫中的其中一個字段(不是propertyid,另一個不相關的字段)的數據類型,但不是在程序中。我完成忘記了自己的變化。我現在感到很傻。

相關問題