Search code examples
c#sqlasp.netasp.net-coredapper

Sequence contains no elements in asp core and sql server 2016


I need to return info from database with T-SQL and I'm using dapper.

I've written this code:

SELECT *
FROM UserActivetionCode UA 
WHERE UA.Username=@Username 
AND UA.ActivetionCode= @ActivetionCode 
AND UA.ExpireTime > GETDATE()

and I'm using this code:

var find = await roleConnection.QueryFirstAsync(command, new { 
    @ActivetionCode = ActivetionCode, 
    @Username = Username });

but it shows me this error:

Sequence contains no elements


Solution

  • This error means that the query didn't return any results.
    If you don't want to get it, use QueryFirstOrDefaultAsync. This will result with default(T) (T being whatever datatype the query should return) if the query returned no rows.

    However, QueryFirst implies a known order in the resultset, which your query does not provide (as it doesn't have an order by clause) and in any case, I suspect that the combination of Username and ActivetionCode should probably be unique. In that case, I would go with QuerySingleOrDefault, which will throw an exception if the query returned more than one result.