C
C#2mo ago
A Ka Sup

Join to other table in LINQKit Predicate

hello, assume that i have a query
c#
var allClasses = from s in context.Classes select new ClassView {
Id = s.Id,
Name = s.Name,
};
// ClassView
public class ClassView {
public int Id { get; set; }
public string? Name { get; set; }
public List<SubjectView> Subjects { get; set; }
}
// SubjectView
public class SubjectView {
public int Id { get; set; }
public string? Name { get; set; }
}
c#
var allClasses = from s in context.Classes select new ClassView {
Id = s.Id,
Name = s.Name,
};
// ClassView
public class ClassView {
public int Id { get; set; }
public string? Name { get; set; }
public List<SubjectView> Subjects { get; set; }
}
// SubjectView
public class SubjectView {
public int Id { get; set; }
public string? Name { get; set; }
}
The Subject connect to Class through the table ClassSubject. Due to some reasons, i cannot get the list subjects in the allClasses LINQ, so i write this
c#
var listClasses = await allClasses.ToListAsync();
foreach(var c in listClasses) {
c.Subjects = await (from s in ClassSubject where s.ClassId = s.Id join x in context.Subject on s.SubjectId equals x.Id select new SubjectView {
Id = x.Id,
Name = x.Name,
}).ToListAsync();
}
c#
var listClasses = await allClasses.ToListAsync();
foreach(var c in listClasses) {
c.Subjects = await (from s in ClassSubject where s.ClassId = s.Id join x in context.Subject on s.SubjectId equals x.Id select new SubjectView {
Id = x.Id,
Name = x.Name,
}).ToListAsync();
}
so here is my question, when i find the class by some subjects name, like ["Ma", "Li"], i build a predicate with LINQKit, it should be something like this
var predicate = LINQKit.PredicateBuilder.New<ClassView>(false);
foreach(var q in querySubject) {
predicate = predicate.Or(s => s.Name.Contains(q));
}
allClasses = allClasses.Where(predicate);
var predicate = LINQKit.PredicateBuilder.New<ClassView>(false);
foreach(var q in querySubject) {
predicate = predicate.Or(s => s.Name.Contains(q));
}
allClasses = allClasses.Where(predicate);
But it's wrong, the func in Or()belongs to Class, not Subject. i need this predicate runs before the listClasses is defined, but i don't know how to join to the table Subject. Can anyone please help me. Thank you!
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server