Dapper - QueryMultiple - 3个表

时间:2016-06-15 08:30:40

标签: dapper

我有这样的关系: Order Link Invoice tables

如何使用QueryMultiple实体检索订单实体和发票实体中的信息?

由于

2 个答案:

答案 0 :(得分:2)

当您访问多个结果集时使用

QueryMultiple,即多个select,如:

select * from Order where Id=@id
select * from Invoice where Id = (...probably some sub-query)

目前,没有内置的API可以将这种类型的查询拼接在一起;相反,你会做类似的事情:

using(var multi = conn.QueryMultiple(...)) {
    var order = multi.ReadSingle<Order>();
    order.Invoice = multi.ReadSingleOrDefault<Invoice>(); // could be null if 0 rows
    return order;
}

我想为这个场景添加一个改进的API,但是表达&#34;将此加入到使用此属性作为关联的地方非常尴尬,其中{this}。{ SomeMember}等于{that}。{SomeOtherMember}&#34;。

但是,如果您实际上正在执行单个查询,请执行以下操作:

select o.*, i.*
from Order o
left outer join Link l on ...
left outer join Invoice i on ...
where o.Id = @id

然后你可以使用各种Query<,...,>重载;例如:

int id = ...
var order = conn.Query<Order, Invoice, Order>(sql,
    (x,y) => {x.Invoice = y; return x;}, args: new { id }, splitOn: "NumOrder").Single();

答案 1 :(得分:0)

三个表的通用代码:

public static Tuple<IEnumerable<T1>, IEnumerable<T2>, IEnumerable<T3>> ExecuteQueryMultiple<T1, T2, T3>(string sql, object parameters,
                                        Func<GridReader, IEnumerable<T1>> func1,
                                        Func<GridReader, IEnumerable<T2>> func2,
                                        Func<GridReader, IEnumerable<T3>> func3)
        {
            var objs = getMultiple(sql, parameters, func1, func2, func3);
            return Tuple.Create(objs[0] as IEnumerable<T1>, objs[1] as IEnumerable<T2>, objs[2] as IEnumerable<T3>);
        }

private static List<object> getMultiple(string procedureName, object param, params Func<GridReader, object>[] readerFuncs)
        {
            var returnResults = new List<object>();
            using (SqlConnection sqlCon = new SqlConnection(connectionString))
            {
                var gridReader = sqlCon.QueryMultiple(procedureName, param, commandType: CommandType.StoredProcedure);

                foreach (var readerFunc in readerFuncs)
                {
                    var obj = readerFunc(gridReader);
                    returnResults.Add(obj);
                }
            }
            return returnResults;
        }

控制器:

[HttpPost]
        public ActionResult GetCommodityDetails(int ID)
        {
            var data = new List<Commodity>();
            DynamicParameters param = new DynamicParameters();
            param.Add("@ATTRIBUTETYPE", "Your parameter");
            param.Add("@CID", Your parameter);
            var result = DapperORM.ExecuteQueryMultiple("Store procedure name", param, gr => gr.Read<order>(), gr => gr.Read<Invoice>(), gr => gr.Read<Link>());

            return Json(result, JsonRequestBehavior.AllowGet);
        }

您可以使用此概念。对我有用