John Patrick Po
John Patrick Po

Reputation: 179

In Dapper Multiple Results how do you get the second line query to work when the where clause depends upon the result of the first query?

Get List of customers with their related orders and returns sample:

var sql = @"select * from Customers
select * from Orders where CustomerId = (depends on first query)
select * from Returns where CustomerId = (depends on first query)";

using (var multi = connection.QueryMultiple(sql))
{
   var customer = multi.Read<Customer>().ToList();
   var orders = multi.Read<Order>().ToList();
   var returns = multi.Read<Return>().ToList();
   ...
} 

Upvotes: 5

Views: 1893

Answers (2)

Krishnraj Rana
Krishnraj Rana

Reputation: 6656

As Marc Gravell had already gave you a hint but apart from that below code might help you.

Let say you have this type of model.

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Order> Orders { get; set; }
    public List<Return> Returns { get; set; }
}

And here is your method.

public List<Customer> GetCustomers()
{
    var customerList = new List<Customer>();

    string query = "SELECT Id, " +
                    "[Name] FROM Customers";

    string subsetquery = @"select * from Orders where CustomerId = @Id;
                            select * from Returns where CustomerId = @Id";

    customerList = _connection.Query<Customer>(query);

    foreach (var item in customerList)
    {
        var oPara = new DynamicParameters();
        oPara.Add("@Id", item.Id, dbType: DbType.Int32);

        using (var multi = _connection.QueryMultiple(subsetquery, oPara, commandType: CommandType.Text))
        {
            item.orders = multi.Read<Order>();
            item.returns = multi.Read<Return>();
        }
    }
    return customerList;
}

NOTE: Above code is not tested in VS. So you may have to change as per your requirement.

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062840

This is ultimately an SQL question. There is nothing extra or different dapper does here - if you issue multiple selects as a batch, they must be valid SQL. There are several ways of doing that, involving:

  • local sql variables (typically if one row)
  • temporary tables or (better) table variables
  • joins or sub-queries
  • etc

If you can't construct SQL to do the thing you want, consider running the first query separately instead.

Upvotes: 3

Related Questions