How to get LINQ top (1) when accessing related objects? .Take () and .FirstOrDefault () do not work?

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; // Still active products associated
        }

        if (reasonToInactivate.EnhancementReasons.Select(ea => ea).Where(ea => ea.Inactive == false).Any())
        {
            canInactivate = false; // Still active enhancements associated
        }

        if (reasonToInactivate.SuggestionReasons.Select(sa => sa).Where(sa => sa.Inactive == false).Take(1).ToArray().Any())
        {
            canInactivate = false; // still active suggestions associated
        }

        if ((reasonToInactivate.SessionProductReasons.Select(spr => spr).Where(spr => spr.Inactive == false).FirstOrDefault()) != null)
        {
            canInactivate = false; // Still active sessions associated
        }
        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!

+3
source share
1 answer

Working with such navigation properties can cause problems. Depends on how you configured LazyLoading, what is your base model (like using inheritance associations) and what is the base query for reasonToInactivate.

- .

, - ( ):

if(context.SuggestionReasonsEntitySet.Any(p => p.ReasonId == reasonToActivateId && p.IsActive)) 
{
    canInactivate = false; // Still active enhancements associated
}

, . , , . (.. ), - , .

, , , .

- SQL , , ( )? , ?

+1

All Articles