[英]Dapper multi mapping many to many relationship
I am trying to map an NN relationship with dapper using as DB MySQL. 我正在尝试使用DB MySQL来映射NN与dapper的关系。 This is more or less the code. 这或多或少是代码。
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");
}
The query works fine in a SQL client but when I run the code above I get this exception: "When using the multi-mapping APIs ensure you set the splitOn param if you have keys other than Id. Parameter name: splitOn" 查询在SQL客户端中工作正常,但是当我运行上面的代码时,我得到了这个异常:“当使用多映射API时,如果你有Id以外的密钥,请确保设置splitOn参数。参数名称:splitOn”
Is it even possible to map a NN relationship having an intermediate table (OwnerPets)?...If so...what am I doing wrong? 是否有可能映射具有中间表(OwnerPets)的NN关系?...如果是这样......我做错了什么?
I'm not sure if you can get Dapper to return the data directly as you want but you could load the data such that there is a one-to-one relationship between Owners and Pets and then follow it with LINQ query to group the Pets for each Owner. 我不确定你是否可以让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;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.