Fetch Items in LINQ where child entities fulfill certain conditions - c#

I'm trying to return a list of TrackInformationRecord, done by:
return _trackInformationRepository
.Fetch(t => t.TrackPartId == trackPart.Id && t.IsDeleted == false)
.ToList();
However, the TrackInformationRecord contains a list of SessionInformationRecord in TrackInformationRecord.Sessions and I only want to take Sessions with IsDeleted == false.
I tried the following but it did't work:
return _trackInformationRepository
.Fetch(t => t.TrackPartId == trackPart.Id && t.IsDeleted == false
&& t.Sessions.Where(s => s.IsDeleted == false))
.ToList();
Any advise would be highly appreciated.

If you want to make sure that all Session's object IsDeleted should be false, you want All
return _trackInformationRepository
.Fetch(t => t.TrackPartId == trackPart.Id && !t.IsDeleted
&& t.Sessions.All(s => !s.IsDeleted)).ToList();
But in case, you want any Session's object IsDeleted to be false, you need Any-
return _trackInformationRepository
.Fetch(t => t.TrackPartId == trackPart.Id && !t.IsDeleted
&& t.Sessions.Any(s => !s.IsDeleted)).ToList();
On a side note, instead of writing t.IsDeleted == false, you can write it like !t.IsDeleted.

Related

Linq optional parameters query

I am making a search form that queries my database to show results based on what has been filled out on the form. The only required field is the date which I have working. all the other fields are optional, if an optional field is not filled in it should not be a part of the query. This is the code I have written:
var queryable = context.TransactionJournal.Where(s => s.TransactionDateTime <= transactionDate)
.Where(s => Region == null || Region == s.AcquirerID)
.Where(s => MCC == null || MCC == s.MerchantCategoryCode)
.Where(s => MerchantID == null || MerchantID.Contains(s.MerchantID))
.Where(s => TxnCurrency == null || TxnCurrency.Contains(s.Currency))
.Where(s => TerminalID == null || TerminalID.Contains(s.TerminalID))
.Where(s => TxnAmount.ToString() == null || TxnAmount==(s.TransactionAmount))
.Where(s => BIN == null || BIN.Contains(s.Bin))
.Where(s => MsgType == null || MsgType.Contains(s.MessageType))
.Where(s => MaskedPan == null || MaskedPan.Contains(s.PANM))
.Where(s => ProcessingCode == null || ProcessingCode.Contains(s.ProcessingCode))
.Where(s => ClearPan == null || ClearPan.Contains(s.PAN))
.Where(s => ResponseCode == null || ResponseCode.Contains(s.ResponseCode))
.Where(s => AuthorizationCode == null || AuthorizationCode.Contains(s.AuthorizationCode))
.Where(s => EntryMode == null || EntryMode.Contains(s.PosEntryMode))
.AsQueryable();
Unfortunately it does not work correctly. Can someone tell me what I am missing or if there is a better way to write this?
Took advice from the comments and went through each line and found which line was evaluating false. This fixed my problem.
I think the best you can do there is check first if you should apply the condition and then filter the list.
An example using the code you provided.
var queryable = context.TransactionJournal.Where(s => s.TransactionDateTime <= transactionDate);
if (!string.IsNullOrEmpty(your_objet.Region)
{
var queryable = queryable.Where(x=>x.Region == your_objet.Region).AsQueryable();
}
if (!string.IsNullOrEmpty(your_objet.MCC)
{
var queryable = queryable.Where(x=>x.MCC == your_objet.MCC).AsQueryable();
}
The first line is the entire list, then you check all parameters that you have in the form and evaluate it, if has value the apply the filter to list.
And the end you'll get your list filtered.

Linq to Entity having more than one where conditions

How can I check for more than one condition in the where clause of LINQ to Entities?
How can I check if the value is false or null
.Where(p => (p.Disabled == false || p.Disabled = null));
You can combine conditions using the usual Boolean operators.
Your solution is missing == in the second part of the condition:
.Where(p => (p.Disabled == false || p.Disabled == null));
// Here --------------------^
You can simplify this further, because checking for a nullable bool to be false or null is equivalent to checking for it not being true:
.Where(p => p.Disabled != true);

Dynamically filtering linq lambda expressions

I'm currently trying doing the following.
var groups = MileId == null ? test.Groups.Where(x => x.ProjectId == ProjectId)
: test.Groups.Where(x => x.Milestone == MileId &&
x.ProjectId == ProjectId);
But I also have additional terms that I need to filter groups by:
foreach (var ChartItem in ChartItems)
{
foreach (var StatusItem in ChartItem.ChartStatusItems)
{
foreach (var PriorityItem in StatusItem.ChartPriorityItems)
{
filteredgroups.AddRange(
groups.Where(x => x.Status == StatusItem.StatusID
&& x.Priority == PriorityItem.PriorityID));
}
}
}
This is fine and it works but the nested foreach loops is pretty slow when adding the ranges. If I groups.toList() before the loop, then that statement is slow and the nested loops are fast.
My question is:
Would it be possible to filter groups from the start based on those StatusIds and PriorityIds dynamically? How?
Stackoverflow recommends some articles on Expression Tree's based on my subject line... is that what I need to look into?
Thank you
EDIT:
So I'm doing this now:
foreach (var ChartItem in ChartItems)
{
foreach (var StatusItem in ChartItem.ChartStatusItems)
{
foreach (var PriorityItem in StatusItem.ChartPriorityItems)
{
var groups = MileId == null ? test.Groups.Where(x => x.ProjectId == InspectorProjectId &&
x.Status == StatusItem.StatusID &&
x.Priority == PriorityItem.PriorityID)
: test.Groups.Where(x => x.Milestone == InspectorMileId &&
x.ProjectId == InspectorProjectId &&
x.Status == StatusItem.StatusID &&
x.Priority == PriorityItem.PriorityID);
filteredgroups.AddRange(groups);
}
}
}
It's a big improvement but it's still going to the slow 'test' server for each priority. If I could get it all filtered in 1 go, it would be ideal.
EDIT 2: Oh I don't have access to the db directly :( we access it through an API.
All this should be happening in the database. Just create a view that joins all those tables. It's hard to be faster than a database when intersecting and joining sets of data.
Can you do it with Contains?
var filteredgroups =
test.Groups.Where(x =>
(MileId == null || x.Milestone == MileId) // (replaces ?: in original)
&& x.ProjectId == ProjectId
&& ChartItem.ChartStatusItems.Contains(x.Status)
&& StatusItem.ChartPriorityItems.Contains(x.Priority));
(I'm not sure how Linq-to-Sql and Linq-to-Objects are going to interact wrt performance, but at least it's concise...)
Maybe you can call .Any() within your .Where() and skip the loops entirely.
test.Groups.Where(x => (MileId == null ||
x.Milestone == MileId) &&
x.ProjectId == ProjectId &&
ChartItems.Any(c => c.ChartStatusItems.Any(s => s.StatusId == x.StatusId &&
s.ChartPriorityItems.Any(p => p.PriorityId == x.PriorityId))));
The foreach loops are most likely executing a deferred call, which is most likely hitting your database on each foreach loop. But you don't have to, using SelectMany you can simply build up your query:
var statuses = ChartItems
.SelectMany(x => x.ChartStatusItems)
.Select(i => i.StatusId);
var priorities = ChartItems
.SelectMany(x => x.ChartPriorityItems)
.Select(i => i.PriorityId);
var filtered = groups.Where(x => statuses.Contains(x.Status) &&
priorities.Contains(x.Priority))

How to do optional parameters in LINQ?

Here is what I'm trying to do:
(Dc.DET_Cases.Where(c => c.ProductID == pl.ProductID
&& oldTOR == false ? c.OldTOR == oldTOR :
&& (productLineName.ToInt() == 0 || productLineName.ToInt() == c.ProductLineID)
&& (productCategory.ToInt() == 0 || productCategory.ToInt() == c.ProductCategoryID)
&& (issueType.ToInt() == 0 || issueType.ToInt() == c.IssueTypeID)
&& (issue.ToInt() == 0 || issue.ToInt() == c.IssueID)
)
.FirstOrDefault() != null)
This is the line I'm trying to do.
oldTOR == false ? c.OldTOR == oldTOR :
inside a where LINQ statement. If the value is false then compare the value. If not, then ignore it.
The easiest way to do this is to just set the other option to be true.
Ie: !oldTOR ? c.OldTOR == oldTOR : true
This means that if oldTor is false, then we want to compare OldTor's, otherwise, keep evaluating the rest of the expression.
As an aside, I would split each part of your massive .Where() boolean comparison into individual .Where() statements. This will improve readability and comprehension of your Linq.
Dc.DET_Cases
.Where(c => c.ProductID == pl.ProductID)
.Where(c => !oldTOR ? c.OldTOR == oldTOR : true)
.Where(c => productLineName.ToInt() == 0 || productLineName.ToInt() == c.ProductLineID)
.Where(c => productCategory.ToInt() == 0 || productCategory.ToInt() == c.ProductCategoryID)
.Where(c => issueType.ToInt() == 0 || issueType.ToInt() == c.IssueTypeID)
.Where(c => issue.ToInt() == 0 || issue.ToInt() == c.IssueID)
.FirstOrDefault() != null;
This makes it clear that if oldTor is false then you want to compare, otherwise, pass that statement (true).
I think you can use the LINQ Dynamic Query Library.
And then create a query as you like.
The fastest way to do this is by evaluation paths:
oldTOR && (c.OldTor == oldTOR)
Why is this the fastest? Answer: if oldTOR is false then the whole and statement is false, and there is no need to compare the rest of the statement.

Ternary operator with Linq-to-SQL causing problems?

I have the following Linq-to-SQL statement:
return db.Photos.SingleOrDefault(p => p.PhotoID == id
&& includePending ? true : p.Live);
For includePending I am passing false. In the database, "Live" is true for all but 2 photos.
However instead of returning one photo as expected, it returns ALL photos in the database except for 2! PhotoID is a primary key (thus can only be true for one item) and boolean logic states that FALSE AND TRUE = FALSE. So what's going on here? Why is it ignoring the p.PhotoID == id portion of my query?
I don't remember the full precedence rules by heart, but your condition is equivalent to:
p => (p.PhotoID == id && includePending) ? true : p.Live
whereas you want:
p => p.PhotoID == id && (includePending ? true : p.Live)
Just use the latter form to make it explicit, or even change it to not use the conditional:
p => p.PhotoID == id && (includePending || p.Live)
which I'd argue is simpler. I would suggest that in situations like this you use bracketing to make the logic clearer even when the precedence rules work in your favour.
You could even use two where clauses:
.Where(p => p.PhotoID == id)
.Where(p => includePending || p.live)
or even conditionalise the second:
var query = ...
.Where(p => p.PhotoID == id);
if (!includePending)
{
query = query.Where(p => p.live);
}

Categories