Problem with 1:N relations
AleyCZ opened this issue · comments
We have the following situation: Let's say there is class Tree and class Apple. One tree has multiple apples.
[Table("Trees")]
public class Tree
{
[Key]
[Required]
public int Id { get; set; }
[LeftJoin(TableName = "Apples", Key = "Id", ExternalKey = "TreeId")]
public List<Apple> Apples { get; set; }
}
[Table("Apples")]
public class Apple
{
[Key]
[Required]
public int Id { get; set; }
[Required]
public int TreeId { get; set; }
}
I want to retrieve one Tree object with ID=myId with all its Apples.
-
This is what works correctly:
await repository.FindAllAsync<Apple>(t => t.Id == myId, t => t.Apples).FirstOrDefault()
-
This is what does not work:
await repository.FindAsync<Apple>(t => t.Id == myId, t => t.Apples)
-
And this also does not work:
await repository.FindByIdAsync<Apple>(myId, t => t.Apples)
While the first call correctly returns the Tree object with the list of all its Apples, the second and third calls both return only one single Apple in that List collection.
Please tell me if I am doing something wrong or this is a bug in your software.
I have some additional information.
We use nuget version 1.8.3 which is somewhat older, but we had even worse experience with newer versions so we stick with that one. I tried to investigate what exact SQL query is being created by SqlGenerator<Tree>
here, in the case of FindByIdAsync
method. We use MSSQL database.
nuget 1.8.3 creates a valid SQL query but there is TOP 1 in it so it returns only a single Apple per Tree.
nuget 1.11.0 creates an invalid SQL query with missing table names (see the source code below), and again TOP 1 is there
nuget 1.18.0 is partially fixed version of 1.11.0 - TOP 1 is not there and table names are there, but there are errors at the end with empty AS and something missing in ON clause (there are two spaces between AS ON - this is not visible in this viewer)
SQL generated by nuget 1.8.3:
SELECT TOP 1 Trees.Id, Apples.Id FROM Trees LEFT JOIN Apples ON Trees.Id = Apples.TreeId WHERE Trees.Id = @Id
SQL generated by nuget 1.11.0:
SELECT TOP 1 Trees.Id, .Id FROM Trees LEFT JOIN Apples AS ON Trees.Id = .TreeId WHERE Trees.Id = @Id
SQL generated by nuget 1.18.0:
SELECT Trees.Id, Apples.Id FROM Trees Apples AS ON Trees.Id = .TreeId WHERE Trees.Id = @Id