How to FirstOrDefault() with Dapper

dapper

Question

I am having problems returning a single object from a Dapper query. I have a simple query and I want to get the first object from the returned collection. What am I missing?

using (SqlConnection sqlConnection = new SqlConnection(GetConnectionString()))
{
    string query = @"select * from order";
    sqlConnection.Open();

    // Works
    var orders = sqlConnection.Query<OrderModel>(query);

    // Does Not Work ERROR: "does not contain a definition for 'FirstOrDefault' and 
    // no extension method 'FirstOrDefault' 
    // accepting a first argument of type 'System.Collections.Generic.IEnumerable<OrderModel>'"
    var order = sqlConnection.Query<OrderModel>(query).FirstOrDefault();                                                                        
}

Accepted Answer

You are getting this error because you have not added the namespace

using System.Linq

in your cs file.




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why