Dapper多映射多对多的关系

时间:2016-06-23 12:57:42

标签: c# sql dapper

我正在尝试使用DB MySQL来映射与dapper的N-N关系。这或多或少都是代码。

        var query = new StringBuilder();
        query.Append("SELECT O.Id, O.Email, O.Status, P.Name FROM Owners AS O");
        query.Append(" INNER JOIN OwnerPets OP ON OP.OwnerId = O.Id");
        query.Append(" INNER JOIN Pets AS P ON P.Id = OP.PetId");
        query.Append(" WHERE O.Status = @Status;");

        using (var dbConnection = CreateConnection())
        {
            return dbConnection.Query<Owner, IEnumerable<Pet>, Owner>(query.ToString(), (owner, pets) =>
            {
                owner.Pets = pets.ToList();
                return Owner;
            }, new { Status = status }, splitOn: "OwnerId, PetId");
        }

查询在SQL客户端中工作正常,但是当我运行上面的代码时,我得到了这个异常:“当使用多映射API时,如果你有Id以外的密钥,请确保设置splitOn参数。参数名称:splitOn”

甚至可以映射具有中间表(OwnerPets)的N-N关系吗?......如果是这样......我做错了什么?

1 个答案:

答案 0 :(得分:8)

我不确定您是否可以让Dapper直接返回数据,但您可以加载数据,以便Owners和Pets之间存在一对一的关系,然后使用LINQ进行关联查询为每个所有者分组宠物。

return dbConnection
    .Query<Owner, Pet, Owner>(
        query,
        (owner, pet) =>
        {
            owner.Pets = owner.Pets ?? new List<Pet>();
            owner.Pets.Add(pet);
            return owner;
        },
        new { Status = status },
        splitOn: "Name"
    )
    .GroupBy(o => o.Id)
    .Select(group =>
    {
        var combinedOwner = group.First();
        combinedOwner.Pets = group.Select(owner => owner.Pets.Single()).ToList();
        return combinedOwner;
    });