简体   繁体   中英

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();
   ...
} 

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM