Simple LINQ to Entities translationWhat is the fastest way to determine if a row exists using Linq to SQL?Combining expression treesLINQ query on a DataTableLearning about LINQMultiple “order by” in LINQWhen to use .First and when to use .FirstOrDefault with LINQ?What is the Java equivalent for LINQ?LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expressionLINQ Aggregate algorithm explainedGroup by in LINQMixing Func and Expression Predicates in Linq To Entity Queriesfilter linq to sql with a entity framework where in

What does this Swiss banner/blazon/coat of arms/flag stand for?

What election rules and voting rights are guaranteed by the US Constitution?

Hard for me to understand one tip written in "The as-if rule" of cppreference

English idiomatic equivalents of 能骗就骗 (if you can cheat, then cheat)

Why wasn't ASCII designed with a contiguous alphanumeric character order?

Should Catholics in a state of grace call themselves sinners?

Fully submerged water bath for stove top baking?

Why should I allow multiple IPs on a website for a single session?

Can US Supreme Court justices / judges be "rotated" out against their will?

Two palindromes are not enough

Why isn't UDP with reliability (implemented at Application layer) a substitute of TCP?

Russian equivalents of 能骗就骗 (if you can cheat, then cheat)

Installed software from source, how to say yum not to install it from package?

Does a lens with a bigger max. aperture focus faster than a lens with a smaller max. aperture?

Word ending in "-ine" for rat-like

Robots in a spaceship

How useful would a hydroelectric power plant be in the post-apocalypse world?

Can I take Amul cottage cheese from India to Netherlands?

How does the 'five minute adventuring day' affect class balance?

Why doesn't SpaceX land boosters in Africa?

How soon after takeoff can you recline your airplane seat?

Does "boire un jus" tend to mean "coffee" or "juice of fruit"?

What verb for taking advantage fits in "I don't want to ________ on the friendship"?

I just started; should I accept a farewell lunch for a coworker I don't know?



Simple LINQ to Entities translation


What is the fastest way to determine if a row exists using Linq to SQL?Combining expression treesLINQ query on a DataTableLearning about LINQMultiple “order by” in LINQWhen to use .First and when to use .FirstOrDefault with LINQ?What is the Java equivalent for LINQ?LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expressionLINQ Aggregate algorithm explainedGroup by in LINQMixing Func and Expression Predicates in Linq To Entity Queriesfilter linq to sql with a entity framework where in













3















Before anyone jumps on a mark as duplicate, I have looked and everyone is doing something slightly more complicated than I am trying.



So I'm working on a database where there's a lot of data to check and LINQ's Any() extension translated to SQL isn't as fast as SQL's Count(1) > 0, so everywhere I'm writing:



var someBool = Ctx.SomeEntities.Count(x => x.RelatedEntity.Count(y => y.SomeProperty == SomeValue) > 0) > 0;



In Pseudo: Does any of my entities have a relationship with some other entity that has a property with a value of SomeValue.




This works fine and it works fast. However, it's not exactly readable (and I have lots of them, more embedded than that in cases) so what I'd like to do is replace it with:



var someBool = Ctx.SomeEntities.AnyX(x => x.RelatedEntity.AnyX(y => y.SomeProperty == SomeValue));


with:



public static bool AnyX<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) => source.Count(predicate) > 0;


So you see I'm not doing anything that LINQ can't translate to SQL, I'm not doing anything that LINQ doesn't already translate to SQL, but just by creating an additional extension I get:




LINQ to Entities does not recognize the method Boolean AnyX etc...




There must be some way of writing my extension or some way of telling LINQ just to take a look at the code and you'll see you can do it.










share|improve this question



















  • 1





    Why are you using AnyX instead of just Any?

    – jdweng
    Mar 25 at 12:06






  • 1





    I see 2 big problems, first EF deals with Expressions, not delegates; pass an Expression<Func<TSource, bool>> instead of a Func<TSource, bool>, and it needs to extend IQueryable<>, not IEnumerable.

    – Bradley Uffner
    Mar 25 at 12:33







  • 1





    @Tod You copied the code for the IEnumerable version of Any. The IQueryable version is different. IEnumerable Version, IQueryable version

    – Bradley Uffner
    Mar 25 at 16:13






  • 1





    It is critically important that you understand the difference between extending IEnumerable and IQueryable when trying to "enhance" entity framework in this way. If you are operating on an IEnumerable, it will run on the local computer, it will NOT be translated in to SQL.

    – Bradley Uffner
    Mar 25 at 16:16







  • 1





    See stackoverflow.com/a/36736907/1625737

    – haim770
    Mar 25 at 16:25















3















Before anyone jumps on a mark as duplicate, I have looked and everyone is doing something slightly more complicated than I am trying.



So I'm working on a database where there's a lot of data to check and LINQ's Any() extension translated to SQL isn't as fast as SQL's Count(1) > 0, so everywhere I'm writing:



var someBool = Ctx.SomeEntities.Count(x => x.RelatedEntity.Count(y => y.SomeProperty == SomeValue) > 0) > 0;



In Pseudo: Does any of my entities have a relationship with some other entity that has a property with a value of SomeValue.




This works fine and it works fast. However, it's not exactly readable (and I have lots of them, more embedded than that in cases) so what I'd like to do is replace it with:



var someBool = Ctx.SomeEntities.AnyX(x => x.RelatedEntity.AnyX(y => y.SomeProperty == SomeValue));


with:



public static bool AnyX<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) => source.Count(predicate) > 0;


So you see I'm not doing anything that LINQ can't translate to SQL, I'm not doing anything that LINQ doesn't already translate to SQL, but just by creating an additional extension I get:




LINQ to Entities does not recognize the method Boolean AnyX etc...




There must be some way of writing my extension or some way of telling LINQ just to take a look at the code and you'll see you can do it.










share|improve this question



















  • 1





    Why are you using AnyX instead of just Any?

    – jdweng
    Mar 25 at 12:06






  • 1





    I see 2 big problems, first EF deals with Expressions, not delegates; pass an Expression<Func<TSource, bool>> instead of a Func<TSource, bool>, and it needs to extend IQueryable<>, not IEnumerable.

    – Bradley Uffner
    Mar 25 at 12:33







  • 1





    @Tod You copied the code for the IEnumerable version of Any. The IQueryable version is different. IEnumerable Version, IQueryable version

    – Bradley Uffner
    Mar 25 at 16:13






  • 1





    It is critically important that you understand the difference between extending IEnumerable and IQueryable when trying to "enhance" entity framework in this way. If you are operating on an IEnumerable, it will run on the local computer, it will NOT be translated in to SQL.

    – Bradley Uffner
    Mar 25 at 16:16







  • 1





    See stackoverflow.com/a/36736907/1625737

    – haim770
    Mar 25 at 16:25













3












3








3








Before anyone jumps on a mark as duplicate, I have looked and everyone is doing something slightly more complicated than I am trying.



So I'm working on a database where there's a lot of data to check and LINQ's Any() extension translated to SQL isn't as fast as SQL's Count(1) > 0, so everywhere I'm writing:



var someBool = Ctx.SomeEntities.Count(x => x.RelatedEntity.Count(y => y.SomeProperty == SomeValue) > 0) > 0;



In Pseudo: Does any of my entities have a relationship with some other entity that has a property with a value of SomeValue.




This works fine and it works fast. However, it's not exactly readable (and I have lots of them, more embedded than that in cases) so what I'd like to do is replace it with:



var someBool = Ctx.SomeEntities.AnyX(x => x.RelatedEntity.AnyX(y => y.SomeProperty == SomeValue));


with:



public static bool AnyX<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) => source.Count(predicate) > 0;


So you see I'm not doing anything that LINQ can't translate to SQL, I'm not doing anything that LINQ doesn't already translate to SQL, but just by creating an additional extension I get:




LINQ to Entities does not recognize the method Boolean AnyX etc...




There must be some way of writing my extension or some way of telling LINQ just to take a look at the code and you'll see you can do it.










share|improve this question
















Before anyone jumps on a mark as duplicate, I have looked and everyone is doing something slightly more complicated than I am trying.



So I'm working on a database where there's a lot of data to check and LINQ's Any() extension translated to SQL isn't as fast as SQL's Count(1) > 0, so everywhere I'm writing:



var someBool = Ctx.SomeEntities.Count(x => x.RelatedEntity.Count(y => y.SomeProperty == SomeValue) > 0) > 0;



In Pseudo: Does any of my entities have a relationship with some other entity that has a property with a value of SomeValue.




This works fine and it works fast. However, it's not exactly readable (and I have lots of them, more embedded than that in cases) so what I'd like to do is replace it with:



var someBool = Ctx.SomeEntities.AnyX(x => x.RelatedEntity.AnyX(y => y.SomeProperty == SomeValue));


with:



public static bool AnyX<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) => source.Count(predicate) > 0;


So you see I'm not doing anything that LINQ can't translate to SQL, I'm not doing anything that LINQ doesn't already translate to SQL, but just by creating an additional extension I get:




LINQ to Entities does not recognize the method Boolean AnyX etc...




There must be some way of writing my extension or some way of telling LINQ just to take a look at the code and you'll see you can do it.







c# linq entity-framework-6 extension-methods






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 26 at 9:08







Tod

















asked Mar 25 at 12:02









TodTod

8689 silver badges20 bronze badges




8689 silver badges20 bronze badges







  • 1





    Why are you using AnyX instead of just Any?

    – jdweng
    Mar 25 at 12:06






  • 1





    I see 2 big problems, first EF deals with Expressions, not delegates; pass an Expression<Func<TSource, bool>> instead of a Func<TSource, bool>, and it needs to extend IQueryable<>, not IEnumerable.

    – Bradley Uffner
    Mar 25 at 12:33







  • 1





    @Tod You copied the code for the IEnumerable version of Any. The IQueryable version is different. IEnumerable Version, IQueryable version

    – Bradley Uffner
    Mar 25 at 16:13






  • 1





    It is critically important that you understand the difference between extending IEnumerable and IQueryable when trying to "enhance" entity framework in this way. If you are operating on an IEnumerable, it will run on the local computer, it will NOT be translated in to SQL.

    – Bradley Uffner
    Mar 25 at 16:16







  • 1





    See stackoverflow.com/a/36736907/1625737

    – haim770
    Mar 25 at 16:25












  • 1





    Why are you using AnyX instead of just Any?

    – jdweng
    Mar 25 at 12:06






  • 1





    I see 2 big problems, first EF deals with Expressions, not delegates; pass an Expression<Func<TSource, bool>> instead of a Func<TSource, bool>, and it needs to extend IQueryable<>, not IEnumerable.

    – Bradley Uffner
    Mar 25 at 12:33







  • 1





    @Tod You copied the code for the IEnumerable version of Any. The IQueryable version is different. IEnumerable Version, IQueryable version

    – Bradley Uffner
    Mar 25 at 16:13






  • 1





    It is critically important that you understand the difference between extending IEnumerable and IQueryable when trying to "enhance" entity framework in this way. If you are operating on an IEnumerable, it will run on the local computer, it will NOT be translated in to SQL.

    – Bradley Uffner
    Mar 25 at 16:16







  • 1





    See stackoverflow.com/a/36736907/1625737

    – haim770
    Mar 25 at 16:25







1




1





Why are you using AnyX instead of just Any?

– jdweng
Mar 25 at 12:06





Why are you using AnyX instead of just Any?

– jdweng
Mar 25 at 12:06




1




1





I see 2 big problems, first EF deals with Expressions, not delegates; pass an Expression<Func<TSource, bool>> instead of a Func<TSource, bool>, and it needs to extend IQueryable<>, not IEnumerable.

– Bradley Uffner
Mar 25 at 12:33






I see 2 big problems, first EF deals with Expressions, not delegates; pass an Expression<Func<TSource, bool>> instead of a Func<TSource, bool>, and it needs to extend IQueryable<>, not IEnumerable.

– Bradley Uffner
Mar 25 at 12:33





1




1





@Tod You copied the code for the IEnumerable version of Any. The IQueryable version is different. IEnumerable Version, IQueryable version

– Bradley Uffner
Mar 25 at 16:13





@Tod You copied the code for the IEnumerable version of Any. The IQueryable version is different. IEnumerable Version, IQueryable version

– Bradley Uffner
Mar 25 at 16:13




1




1





It is critically important that you understand the difference between extending IEnumerable and IQueryable when trying to "enhance" entity framework in this way. If you are operating on an IEnumerable, it will run on the local computer, it will NOT be translated in to SQL.

– Bradley Uffner
Mar 25 at 16:16






It is critically important that you understand the difference between extending IEnumerable and IQueryable when trying to "enhance" entity framework in this way. If you are operating on an IEnumerable, it will run on the local computer, it will NOT be translated in to SQL.

– Bradley Uffner
Mar 25 at 16:16





1




1





See stackoverflow.com/a/36736907/1625737

– haim770
Mar 25 at 16:25





See stackoverflow.com/a/36736907/1625737

– haim770
Mar 25 at 16:25










1 Answer
1






active

oldest

votes


















0














Not an answer to your specific question, but I suggest you rethink how you're approaching the query.



Let's use some descriptive names that make it easier to understand: do any households have a resident with the first name of "Bobby"?



// your way
Ctx.Households.Count( hh => hh.Residents.Count( r => r.FirstName == "Bobby" ) > 0 ) > 0


Yuck, it's backwards. Start with residents:



Ctx.Residents.Count( r => 
r.FirstName == "Bobby"
&& r.Household != null ) // if needed
> 0;


Now, will that generate SQL significantly different than the below?



Ctx.Residents.Any( r => r.FirstName == "Bobby" && r.Household != null)


edit:



Here's a true MCVE that results in the opposite of your conclusion:



/*
create table TestDatum
(
TestValue nchar(36) not null
)
*/

/*
set nocount on
declare @count int
declare @start datetime
declare @end datetime
set @count = 0

set @start = GETDATE()

while @count < 14000000
begin
insert TestDatum values( CONVERT(nchar(36), NEWID()) )

set @count = @count + 1

if (@count % 100000) = 0
begin
print convert(nvarchar, @count)
end
end

set @end = GETDATE()

select CONVERT(nvarchar, DATEDIFF(ms, @start, @end))
*/

/*
-- "Any" test
declare @startdt datetime, @enddt datetime
set @startdt = GETDATE()
DECLARE @p0 NVarChar(1000) = '%abcdef%'

SELECT
(CASE
WHEN EXISTS(
SELECT NULL AS [EMPTY]
FROM TestDatum AS [t0]
WHERE [t0].TestValue LIKE @p0
) THEN 1
ELSE 0
END) AS [value]
set @enddt = GETDATE()
select DATEDIFF(ms, @startdt, @enddt) -- ~7000ms
*/
/*
-- "Count" test
declare @startdt datetime, @enddt datetime
set @startdt = GETDATE()
-- Region Parameters
DECLARE @p0 NVarChar(1000) = '%abcdef%'
-- EndRegion
SELECT COUNT(*) AS [value]
FROM TestDatum AS [t0]
WHERE [t0].TestValue LIKE @p0
set @enddt = GETDATE()
select DATEDIFF(ms, @startdt, @enddt) -- > 48000ms
*/





share|improve this answer

























  • Yes SQL Translates any to: CASE WHEN EXISTS( SELECT NULL AS [EMPTY] FROM. Count is just COUNT

    – Tod
    Apr 4 at 12:46












  • @Tod - ok, and you're saying counting all records is somehow faster or more optimal than short circuiting upon finding the first record?

    – Moho
    Apr 4 at 14:05











  • Yes, that's exactly what I'm saying. I don't know why, I've posted on SO before, check the comments from the question for the link. Some data can be comparable in terms of the speed of the two methods. Other times it can be much much quicker to Count.

    – Tod
    Apr 4 at 15:05











  • Can you provide a MCVE reproducing this behavior?

    – Moho
    Apr 4 at 15:14











  • Like I said, link in the comments for the question. stackoverflow.com/questions/648795/…

    – Tod
    Apr 4 at 15:17










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55337370%2fsimple-linq-to-entities-translation%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














Not an answer to your specific question, but I suggest you rethink how you're approaching the query.



Let's use some descriptive names that make it easier to understand: do any households have a resident with the first name of "Bobby"?



// your way
Ctx.Households.Count( hh => hh.Residents.Count( r => r.FirstName == "Bobby" ) > 0 ) > 0


Yuck, it's backwards. Start with residents:



Ctx.Residents.Count( r => 
r.FirstName == "Bobby"
&& r.Household != null ) // if needed
> 0;


Now, will that generate SQL significantly different than the below?



Ctx.Residents.Any( r => r.FirstName == "Bobby" && r.Household != null)


edit:



Here's a true MCVE that results in the opposite of your conclusion:



/*
create table TestDatum
(
TestValue nchar(36) not null
)
*/

/*
set nocount on
declare @count int
declare @start datetime
declare @end datetime
set @count = 0

set @start = GETDATE()

while @count < 14000000
begin
insert TestDatum values( CONVERT(nchar(36), NEWID()) )

set @count = @count + 1

if (@count % 100000) = 0
begin
print convert(nvarchar, @count)
end
end

set @end = GETDATE()

select CONVERT(nvarchar, DATEDIFF(ms, @start, @end))
*/

/*
-- "Any" test
declare @startdt datetime, @enddt datetime
set @startdt = GETDATE()
DECLARE @p0 NVarChar(1000) = '%abcdef%'

SELECT
(CASE
WHEN EXISTS(
SELECT NULL AS [EMPTY]
FROM TestDatum AS [t0]
WHERE [t0].TestValue LIKE @p0
) THEN 1
ELSE 0
END) AS [value]
set @enddt = GETDATE()
select DATEDIFF(ms, @startdt, @enddt) -- ~7000ms
*/
/*
-- "Count" test
declare @startdt datetime, @enddt datetime
set @startdt = GETDATE()
-- Region Parameters
DECLARE @p0 NVarChar(1000) = '%abcdef%'
-- EndRegion
SELECT COUNT(*) AS [value]
FROM TestDatum AS [t0]
WHERE [t0].TestValue LIKE @p0
set @enddt = GETDATE()
select DATEDIFF(ms, @startdt, @enddt) -- > 48000ms
*/





share|improve this answer

























  • Yes SQL Translates any to: CASE WHEN EXISTS( SELECT NULL AS [EMPTY] FROM. Count is just COUNT

    – Tod
    Apr 4 at 12:46












  • @Tod - ok, and you're saying counting all records is somehow faster or more optimal than short circuiting upon finding the first record?

    – Moho
    Apr 4 at 14:05











  • Yes, that's exactly what I'm saying. I don't know why, I've posted on SO before, check the comments from the question for the link. Some data can be comparable in terms of the speed of the two methods. Other times it can be much much quicker to Count.

    – Tod
    Apr 4 at 15:05











  • Can you provide a MCVE reproducing this behavior?

    – Moho
    Apr 4 at 15:14











  • Like I said, link in the comments for the question. stackoverflow.com/questions/648795/…

    – Tod
    Apr 4 at 15:17















0














Not an answer to your specific question, but I suggest you rethink how you're approaching the query.



Let's use some descriptive names that make it easier to understand: do any households have a resident with the first name of "Bobby"?



// your way
Ctx.Households.Count( hh => hh.Residents.Count( r => r.FirstName == "Bobby" ) > 0 ) > 0


Yuck, it's backwards. Start with residents:



Ctx.Residents.Count( r => 
r.FirstName == "Bobby"
&& r.Household != null ) // if needed
> 0;


Now, will that generate SQL significantly different than the below?



Ctx.Residents.Any( r => r.FirstName == "Bobby" && r.Household != null)


edit:



Here's a true MCVE that results in the opposite of your conclusion:



/*
create table TestDatum
(
TestValue nchar(36) not null
)
*/

/*
set nocount on
declare @count int
declare @start datetime
declare @end datetime
set @count = 0

set @start = GETDATE()

while @count < 14000000
begin
insert TestDatum values( CONVERT(nchar(36), NEWID()) )

set @count = @count + 1

if (@count % 100000) = 0
begin
print convert(nvarchar, @count)
end
end

set @end = GETDATE()

select CONVERT(nvarchar, DATEDIFF(ms, @start, @end))
*/

/*
-- "Any" test
declare @startdt datetime, @enddt datetime
set @startdt = GETDATE()
DECLARE @p0 NVarChar(1000) = '%abcdef%'

SELECT
(CASE
WHEN EXISTS(
SELECT NULL AS [EMPTY]
FROM TestDatum AS [t0]
WHERE [t0].TestValue LIKE @p0
) THEN 1
ELSE 0
END) AS [value]
set @enddt = GETDATE()
select DATEDIFF(ms, @startdt, @enddt) -- ~7000ms
*/
/*
-- "Count" test
declare @startdt datetime, @enddt datetime
set @startdt = GETDATE()
-- Region Parameters
DECLARE @p0 NVarChar(1000) = '%abcdef%'
-- EndRegion
SELECT COUNT(*) AS [value]
FROM TestDatum AS [t0]
WHERE [t0].TestValue LIKE @p0
set @enddt = GETDATE()
select DATEDIFF(ms, @startdt, @enddt) -- > 48000ms
*/





share|improve this answer

























  • Yes SQL Translates any to: CASE WHEN EXISTS( SELECT NULL AS [EMPTY] FROM. Count is just COUNT

    – Tod
    Apr 4 at 12:46












  • @Tod - ok, and you're saying counting all records is somehow faster or more optimal than short circuiting upon finding the first record?

    – Moho
    Apr 4 at 14:05











  • Yes, that's exactly what I'm saying. I don't know why, I've posted on SO before, check the comments from the question for the link. Some data can be comparable in terms of the speed of the two methods. Other times it can be much much quicker to Count.

    – Tod
    Apr 4 at 15:05











  • Can you provide a MCVE reproducing this behavior?

    – Moho
    Apr 4 at 15:14











  • Like I said, link in the comments for the question. stackoverflow.com/questions/648795/…

    – Tod
    Apr 4 at 15:17













0












0








0







Not an answer to your specific question, but I suggest you rethink how you're approaching the query.



Let's use some descriptive names that make it easier to understand: do any households have a resident with the first name of "Bobby"?



// your way
Ctx.Households.Count( hh => hh.Residents.Count( r => r.FirstName == "Bobby" ) > 0 ) > 0


Yuck, it's backwards. Start with residents:



Ctx.Residents.Count( r => 
r.FirstName == "Bobby"
&& r.Household != null ) // if needed
> 0;


Now, will that generate SQL significantly different than the below?



Ctx.Residents.Any( r => r.FirstName == "Bobby" && r.Household != null)


edit:



Here's a true MCVE that results in the opposite of your conclusion:



/*
create table TestDatum
(
TestValue nchar(36) not null
)
*/

/*
set nocount on
declare @count int
declare @start datetime
declare @end datetime
set @count = 0

set @start = GETDATE()

while @count < 14000000
begin
insert TestDatum values( CONVERT(nchar(36), NEWID()) )

set @count = @count + 1

if (@count % 100000) = 0
begin
print convert(nvarchar, @count)
end
end

set @end = GETDATE()

select CONVERT(nvarchar, DATEDIFF(ms, @start, @end))
*/

/*
-- "Any" test
declare @startdt datetime, @enddt datetime
set @startdt = GETDATE()
DECLARE @p0 NVarChar(1000) = '%abcdef%'

SELECT
(CASE
WHEN EXISTS(
SELECT NULL AS [EMPTY]
FROM TestDatum AS [t0]
WHERE [t0].TestValue LIKE @p0
) THEN 1
ELSE 0
END) AS [value]
set @enddt = GETDATE()
select DATEDIFF(ms, @startdt, @enddt) -- ~7000ms
*/
/*
-- "Count" test
declare @startdt datetime, @enddt datetime
set @startdt = GETDATE()
-- Region Parameters
DECLARE @p0 NVarChar(1000) = '%abcdef%'
-- EndRegion
SELECT COUNT(*) AS [value]
FROM TestDatum AS [t0]
WHERE [t0].TestValue LIKE @p0
set @enddt = GETDATE()
select DATEDIFF(ms, @startdt, @enddt) -- > 48000ms
*/





share|improve this answer















Not an answer to your specific question, but I suggest you rethink how you're approaching the query.



Let's use some descriptive names that make it easier to understand: do any households have a resident with the first name of "Bobby"?



// your way
Ctx.Households.Count( hh => hh.Residents.Count( r => r.FirstName == "Bobby" ) > 0 ) > 0


Yuck, it's backwards. Start with residents:



Ctx.Residents.Count( r => 
r.FirstName == "Bobby"
&& r.Household != null ) // if needed
> 0;


Now, will that generate SQL significantly different than the below?



Ctx.Residents.Any( r => r.FirstName == "Bobby" && r.Household != null)


edit:



Here's a true MCVE that results in the opposite of your conclusion:



/*
create table TestDatum
(
TestValue nchar(36) not null
)
*/

/*
set nocount on
declare @count int
declare @start datetime
declare @end datetime
set @count = 0

set @start = GETDATE()

while @count < 14000000
begin
insert TestDatum values( CONVERT(nchar(36), NEWID()) )

set @count = @count + 1

if (@count % 100000) = 0
begin
print convert(nvarchar, @count)
end
end

set @end = GETDATE()

select CONVERT(nvarchar, DATEDIFF(ms, @start, @end))
*/

/*
-- "Any" test
declare @startdt datetime, @enddt datetime
set @startdt = GETDATE()
DECLARE @p0 NVarChar(1000) = '%abcdef%'

SELECT
(CASE
WHEN EXISTS(
SELECT NULL AS [EMPTY]
FROM TestDatum AS [t0]
WHERE [t0].TestValue LIKE @p0
) THEN 1
ELSE 0
END) AS [value]
set @enddt = GETDATE()
select DATEDIFF(ms, @startdt, @enddt) -- ~7000ms
*/
/*
-- "Count" test
declare @startdt datetime, @enddt datetime
set @startdt = GETDATE()
-- Region Parameters
DECLARE @p0 NVarChar(1000) = '%abcdef%'
-- EndRegion
SELECT COUNT(*) AS [value]
FROM TestDatum AS [t0]
WHERE [t0].TestValue LIKE @p0
set @enddt = GETDATE()
select DATEDIFF(ms, @startdt, @enddt) -- > 48000ms
*/






share|improve this answer














share|improve this answer



share|improve this answer








edited Apr 4 at 18:14

























answered Mar 29 at 19:51









MohoMoho

11.5k1 gold badge18 silver badges23 bronze badges




11.5k1 gold badge18 silver badges23 bronze badges












  • Yes SQL Translates any to: CASE WHEN EXISTS( SELECT NULL AS [EMPTY] FROM. Count is just COUNT

    – Tod
    Apr 4 at 12:46












  • @Tod - ok, and you're saying counting all records is somehow faster or more optimal than short circuiting upon finding the first record?

    – Moho
    Apr 4 at 14:05











  • Yes, that's exactly what I'm saying. I don't know why, I've posted on SO before, check the comments from the question for the link. Some data can be comparable in terms of the speed of the two methods. Other times it can be much much quicker to Count.

    – Tod
    Apr 4 at 15:05











  • Can you provide a MCVE reproducing this behavior?

    – Moho
    Apr 4 at 15:14











  • Like I said, link in the comments for the question. stackoverflow.com/questions/648795/…

    – Tod
    Apr 4 at 15:17

















  • Yes SQL Translates any to: CASE WHEN EXISTS( SELECT NULL AS [EMPTY] FROM. Count is just COUNT

    – Tod
    Apr 4 at 12:46












  • @Tod - ok, and you're saying counting all records is somehow faster or more optimal than short circuiting upon finding the first record?

    – Moho
    Apr 4 at 14:05











  • Yes, that's exactly what I'm saying. I don't know why, I've posted on SO before, check the comments from the question for the link. Some data can be comparable in terms of the speed of the two methods. Other times it can be much much quicker to Count.

    – Tod
    Apr 4 at 15:05











  • Can you provide a MCVE reproducing this behavior?

    – Moho
    Apr 4 at 15:14











  • Like I said, link in the comments for the question. stackoverflow.com/questions/648795/…

    – Tod
    Apr 4 at 15:17
















Yes SQL Translates any to: CASE WHEN EXISTS( SELECT NULL AS [EMPTY] FROM. Count is just COUNT

– Tod
Apr 4 at 12:46






Yes SQL Translates any to: CASE WHEN EXISTS( SELECT NULL AS [EMPTY] FROM. Count is just COUNT

– Tod
Apr 4 at 12:46














@Tod - ok, and you're saying counting all records is somehow faster or more optimal than short circuiting upon finding the first record?

– Moho
Apr 4 at 14:05





@Tod - ok, and you're saying counting all records is somehow faster or more optimal than short circuiting upon finding the first record?

– Moho
Apr 4 at 14:05













Yes, that's exactly what I'm saying. I don't know why, I've posted on SO before, check the comments from the question for the link. Some data can be comparable in terms of the speed of the two methods. Other times it can be much much quicker to Count.

– Tod
Apr 4 at 15:05





Yes, that's exactly what I'm saying. I don't know why, I've posted on SO before, check the comments from the question for the link. Some data can be comparable in terms of the speed of the two methods. Other times it can be much much quicker to Count.

– Tod
Apr 4 at 15:05













Can you provide a MCVE reproducing this behavior?

– Moho
Apr 4 at 15:14





Can you provide a MCVE reproducing this behavior?

– Moho
Apr 4 at 15:14













Like I said, link in the comments for the question. stackoverflow.com/questions/648795/…

– Tod
Apr 4 at 15:17





Like I said, link in the comments for the question. stackoverflow.com/questions/648795/…

– Tod
Apr 4 at 15:17






Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55337370%2fsimple-linq-to-entities-translation%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript