Using Dapper you can easily map results of a query to an object or a list of objects. Sometimes you want to select a list of ids like when using an IN
statement, you can accomplish this with the following code:
using (var sqlConnection = new SqlConnection(@"Data Source=localhost;Initial Catalog=MyDb;Integrated Security=True;"))
{
string sql = "select * from [dbo].[MyEntities]e where id in @ids";
var results = sqlConnection.Query<MyEntity>(sql, new { ids = new[] { 3, 4, 5 } });
}
Using the above we create a connection. We use this connection to execute a SELECT
statement with an in clause using the variable @ids
. We provide a class which the result of the query will be mapped to:
[Table("MyEntities")]
public class MyEntity
{
public int Id { get; set; }
public string Text { get; set; }
}
That is all there is to it, let me know what you think in the comments down below!