Using LINQ for Entity Framework and C # objects:
I have a method called CanInactivateReason that checks to see if there are any active related records before allowing the user to inactivate the cause. If the method returns false, then the "DisabledDelete" image is displayed with a hint informing the user why they cannot delete the object in the grid instead of the "Delete" button. My problem is performance when queries return all related objects instead of doing the top 1 for each navigation property.
.Take (1) extension method does not add top (1) to my LINQ to Entities query - why ??
Nor is.Count ()> 0 or .Any () or .Take (1) .ToArray (). Any () or .FirstOrDefault ()! = Null
Here is my method that returns bool, so I would prefer the queries to be on top of 1 - I tried each element below:
public bool CanInactivateReason(Reason reasonToInactivate)
{
bool canInactivate = true;
if (reasonToInactivate.ProductReasons.Select(pa => pa).Where(pa => pa.Inactive == false).Count() > 0)
{
canInactivate = false;
}
if (reasonToInactivate.EnhancementReasons.Select(ea => ea).Where(ea => ea.Inactive == false).Any())
{
canInactivate = false;
}
if (reasonToInactivate.SuggestionReasons.Select(sa => sa).Where(sa => sa.Inactive == false).Take(1).ToArray().Any())
{
canInactivate = false;
}
if ((reasonToInactivate.SessionProductReasons.Select(spr => spr).Where(spr => spr.Inactive == false).FirstOrDefault()) != null)
{
canInactivate = false;
}
return canInactivate;
}
I assume this is related to accessing the related objects of my object, but what can I do to turn these queries into SQL generated top (1)?
Thanks in advance!
source
share