【问题标题】:Dapper throwing invalid cast exception when using strongly-typed query parameters with Sybase ASE在 Sybase ASE 中使用强类型查询参数时,Dapper 抛出无效转换异常
【发布时间】:2012-03-07 23:27:49
【问题描述】:

正如问题标题所述,即使我的存储过程返回一个 int 和一个 DateTime 并且我的班级将其定义为相同,我也会收到 Specified cast is not valid 异常。

public class Foo
{
    public int Id {get; set;}
    public DateTime CreatedDate {get; set;}
}

当我执行这个查询时:

var results = connection.Query("spGetFoo", commandType: CommandType.StoredProcedure);

我得到以下 2 个例外:

InvalidCastException: Specified cast is not valid.
DataException: Error parsing column 1 (Id=1 - Decimal)

InvalidCastException: Specified cast is not valid.
DataException: Error parsing column 2 (CreatedDate=Mar  7 2012  5:52:08:276PM - String)

如果我将Foo 的属性从int 修改为decimal 并将DateTime 修改为string,它会正确填充这些值。但是,这引入了一个额外的步骤,即定义另一个包含正确变量类型的类,然后从 Foo 映射到新类。

我还尝试通过 Dapper 源代码中的 GetTypeDeserializer 来查看发生了什么,但我对 IL emit 不太熟悉。

【问题讨论】:

  • 您确定 spGetFoo 以 int 和 datetime 形式返回吗?你能显示 SQL 和列定义吗?
  • 当然很高兴看到存储过程......

标签: c# dapper


【解决方案1】:

也许问题出在存储过程中,但同时你可以使用

public class Foo
{
    private decimal _dbId;
    public decimal DbId 
    { 
        get { return _dbId; }
        set 
        { 
            _dbId = value;
            _id =(int)value;
        }
    }
    private String _dbCreadtedDate;
    public String DbCreadtedDate 
    { 
        get { return _dbCreadtedDate; }
        set 
        {
            _dbCreadtedDate = value;
            _createdDate = DateTime.Parse(_dbCreadtedDate);
        }
    }
    private int _id;
    public int Id 
    { 
        get { return _id; } 
        set { _id = value; _dbId = value; } 
    }
    private DateTime _createdDate;
    public DateTime CreatedDate 
    { 
        get { return _createdDate; } 
        set { _createdDate = value; _dbCreadtedDate = value.ToString(); } 
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-27
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    • 1970-01-01
    • 2011-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多