价值不是可转换对象

时间:2015-11-16 18:31:29

标签: dapper

我有一个简单的查询和Poco我正在使用Dapper:

var jc = this.dbConnection.ExecuteScalar<JcUser>("SELECT loginid as Username,Password,coalesce(CustomerId,0) as CustomerId,TextProfileId,UxProfileId from \"user\" where id = @id", new {id = id});

波索:

public class JcUser
{

    public string UserName { get; set; }

    public string Password { get; set; }

    public int CustomerId{ get; set; }

    public int TextProfileId { get; set; }

    public int UxProfileId { get; set; }
}

执行此操作时,会抛出一条带有消息

的异常

Value is not a convertible object: System.String to JcUser

堆栈跟踪最终位于:at System.Convert.ToType (System.Object value, System.Type conversionType, IFormatProvider provider, Boolean try_target_to_type)

为什么要这样做呢?

由于

更新:使用var jc = this.dbConnection.Query<JcUser>("SELECT loginid as Username,Password,coalesce(CustomerId,0) as CustomerId,TextProfileId,UxProfileId from \"user\" where id = @id", new {id = id}).First();似乎有效。我也意识到我是一个白痴,而ExecuteScalar只是一个值。但是,我的更新是仅检索一行的最佳方式吗?

1 个答案:

答案 0 :(得分:1)

ExecuteScalar映射到同名的ADO.NET方法。它最多返回一个单元格:一个网格,一行,一列。因此,它不适用于复杂对象,并且不能在您的情况下正常工作,因为您有多个列。

Dapper假设您只使用intstring等简单类型。

在您的情况下,请使用:

var jc = this.dbConnection.Query<JcUser>(
     sql, args).SingleOrDefault();

如果您想避免隐藏的List<>分配,您也可以通过buffered: false