I have inherited some code which is now causing an issue w. The code looks similar to the following (albeit redacted).
public class ObjectX {
public Guid Id { get; set; }
public List<ObjectY> ListOfY { get; set; }
}
public class ObjectY {
public Guid Id { get; set; }
public ObjectX MyX { get; set; }
public ObjectZ MyZ { get; set; }
}
public class ObjectZ
public Guid ObjectXId { get; set; }
public Guid ObjectYId { get; set; }
public ObjectX MyX { get; set; }
public ObjectY MyY { get; set; }
}
So just to be clear,
- ObjectX contains a collection of ObjectY
- ObjectY contains an instance of ObjectZ and ObjectX
- ObjectZ contains an instance of both ObjectX and ObjectY
ModelBuilder has the following:
modelBuilder.Entity<ObjectZ>
.HasIndex(p => new { p.ObjectXId, p.ObjectYId })
.IsUnique();
indicating that ObjectX and ObjectY are unique as a pair but can appear in different combinations.
The query that is being used is
var something = context.ObjectX
.Where(x => x.Id = <somevalue>)
.Include(y => y.ListOfY)
.ThenInclude(z => z.MyZ)
.SingleOrDefault();
The issue I'm encountering is that while the ThenInclude function successfully retrieves the first ObjectZ that matches ObjectY.Id, it doesn't take into account ObjectX.Id.
Is there a way to adjust the query, Fluent definitions, or other aspects to ensure that ObjectX is returned with a list of ObjectY where ObjectY.MyZ matches both ObjectXId and ObjectYId?
I acknowledge that the current state of the database design and other related components may not be optimal, but as previously mentioned, I inherited this setup.