Reputation: 13
I'm new to C# and Entity Framework Core. I have searched a lot for this question but did not found an answer. I have the following three models (I have simplified it):
public class Exercise
{
public int ExerciseId { get; set; }
[Required]
public string ExerciseName { get; set; }
public string Filename { get; set; }
public ICollection<ExerciseClinicalPicture> ExerciseClinicalPicture { get; set; }
}
public class ClinicalPicture
{
[Key]
public int ClinicalPictureId { get; set; }
[Required]
[Display(Name = "Krankheitsbild")]
public string ClinicalPictureName { get; set; }
public ICollection<ExerciseClinicalPicture> ExerciseClinicalPicture { get; set; }
}
public class ExerciseClinicalPicture
{
[Key]
public int ExerciseClinicalPictureId { get; set; }
public int ExerciseId { get; set; }
public Exercise Exercise { get; set; }
public int ClinicalPictureId { get; set; }
public ClinicalPicture ClinicalPicture { get; set; }
}
Now I want to have a query where the result is a collection of all exercises which are associated with a certain clinical picture and the clinicalPicture
is included.
Something like this:
int id = 1;
exercises = _context.Exercise.Where(e => e.ExerciseClinicalPicture.ClinicalPictureId == id)
.Include(m => m.ExerciseClinicalPicture)
.ThenInclude(m => m.ClinicalPicture);
This query throws an error because I can not call ClinicalPictureId
on a collection of ExerciseClinicalPicture
.
Hope my question is OK like this. It is the first time I ask a question on Stackoverflow.
Thanks a lot for your help
Upvotes: 1
Views: 1911
Reputation: 759
Change this:
exercises = _context.Exercise.Where(e => e.ExerciseClinicalPicture.ClinicalPictureId == id)
to this:
exercises = _context.Exercise.Where(e => e.ExerciseClinicalPicture.Any(ec => ec.ExerciseId == id))
Basically, "Get exercises where any of the exercise clinical pictures on the exercise contains the given exercise ID." In your models, ExerciseClinicalPicture is a collection. You have to dig into it once more. Your error is that the property doesn't exist because it's a collection.
And this is how you'd query it. Then you can just do your includes as you would normally.
Upvotes: 2