从数据库问题中检索对象

时间:2013-08-26 22:24:21

标签: c# sql asp.net-mvc visual-studio-2010

过去一小时这一直困扰着我,我无法找出到底出了什么问题。我试图从我们的数据库中检索一个对象以及其他几个对象(返回正常)。我得到了一个例外

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类。

2 个答案:

答案 0 :(得分:0)

问题必须PropertyId在一种类型中定义为int,在另一种类型中定义为string

若是,这应该有效:

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

或者您可以将存储库项目更改为int。

答案 1 :(得分:0)

我找到了问题的解决方案。我的其他同事之一更改了数据库中某个字段(不是propertyid,另一个不相关的字段)的数据类型,但未在程序中更改。我完成了忘记自己的改变。我现在觉得很傻。