Search code examples
c#dapper

Project parameter from SQL query into object


I have the following query which is executed in C# using Dapper.

public async Task<IEnumerable<UserDetails>> GetUsers(DateTime from, DateTime to)
{
    try
    {
        const string query = @"SELECT UserName, ExecutedFromDate as @fromDate
                               FROM UserTable
                               WHERE TransactionDate >= @fromDate 
                                 AND TransactionDate <= @toDate";

        var result = await Connection.QueryAsync<UserDetails>(query, new { fromDate = from, toDate= to });
    }
}

I also have a POCO class:

public class UserDetails 
{ 
    public string UserName { get; set; }
    public DateTime ExecutedFromDate { get; set; }

    public DateTime ExecutedToDate { get; set; }
}

As the UserName in the UserDetails is populated, I want the ExecutedFromDate and ExecutedToDate to hold the values of to and from from the parameters respectively. How can I achieve that? Please help.


Solution

  • Looks like your sql is incorrect.

    SELECT UserName, ExecutedFromDate as @fromDate
    

    Above, you use parameter as alias. If you want to return your input parameters as data from your query, do this

    SELECT UserName, @fromDate fromDate, @toDate toDate...