Can I map a result to Tuple in Dapper?

后端 未结 5 1350
梦谈多话
梦谈多话 2021-01-01 08:49

I am trying to select a list of 2 integer columns map the results to a Tuple. Just as an example:

return connection.Query>(\"sele         


        
5条回答
  •  耶瑟儿~
    2021-01-01 09:50

    This works starting from C# 7. This is a Value Tuple

    public (int Id, DateTime? PublishDate) GetItem(string id)
    {
        const string sqlCommand = "select top 1 Id, PublishDate from Item where Id = @id";
    
        return _connection.Query<(int, DateTime?)>(sqlCommand, new { id }).FirstOrDefault();
    }       
    

    Using the method

    var item = GetItem(123);
    Console.WriteLine($"The publish date of item [{item.Id}] is [{item.PublishDate.Value}]");
    

    Make sure you have installed Dapper 1.50.4 or later.

提交回复
热议问题