I'm trying to filter out the items I pass through to my View in my Controller, and while I have a solution, I'm keen to know the right way to do it, as I'm sure it's not the best.
I have a table of Work Orders and related Tasks for each Work Order. In my site I do not delete rows, but mark them with a WhenDeleted date, so when populating my Work Order View (single, not list) I want a WorkOrder entity with the child Tasks, but I want to filter out the Tasks marked as deleted.
Here's my code, which works, but it seems like I should be able to filter this out with the initial call to save a trip.
if (db.tblWorkOrder.Any(x => x.ID == id))
{
tblWorkOrder model = db.tblWorkOrder.First(x => x.ID == id);
model.tblTask = model.tblTask.Where(x => x.WhenDeleted == null).ToList()
}
Solution: The duplicate question marked here had the answer. There are others with stronger google-fu here, and I think it helped knowing the terminology of what I was trying to do. Anywho, here's the answer for others who find this question first:
db.Configuration.ProxyCreationEnabled = false; // disable lazy-loading
if (db.tblWorkOrder.Any(x => x.ID == id))
{
tblWorkOrder model = db.tblWorkOrder.Where(b => b.ID == id)
.Select(b => new
{
b,
tblTask = b.tblTask.Where(p => p.WhenDeleted == null).OrderBy(x => x.Position)
})
.AsEnumerable()
.Select(x => x.b)
.First();
}