2016-06-23 29 views
6

Sto provando a mappare una relazione N-N con dapper usando come DB MySQL. Questo è più o meno il codice.Dapper multi mapping molte a molte relazioni

 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"); 
     } 

La query funziona bene in un client SQL, ma quando faccio funzionare il codice qui sopra ottengo questa eccezione:. "Quando si utilizza le API multi-mapping assicurarsi di impostare il parametro splitOn se si dispone di chiavi diverse da Id Parametro nome: splitOn "

È persino possibile mappare una relazione NN con una tabella intermedia (OwnerPets)? ... Se sì ... cosa sto facendo male?

risposta

5

Non sono sicuro se è possibile ottenere Dapper per restituire i dati direttamente come si desidera ma è possibile caricare i dati in modo che vi sia una relazione uno a uno tra proprietari e animali domestici e quindi seguirla con query LINQ raggruppare gli animali domestici per ciascun proprietario.

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