Reputation: 1895
I am current refactoring some code that uses Entity Framework.
What I cannot really figure out is the reason why someone called Entities.Any()
, it looks random but the comment says that it is used to override the lazy loaded values. It still make no sense to me as calling Any()
should not modify the underlying collection.
Should I feel comfortable deleting this statement?
The code looks like this:
class MyEFObject {
public virtual ICollection<Entity> Entities { get; set; }
public void SetEntities(ICollection<Entity> entities)
{
// [...]
Entities.Any(); // to override lazyloaded values
Entities = entities.Where(a => a.MyEFObjectId == Id).ToList();
// [...]
}
}
Of course there are no tests so I cannot verify what the intended behaviour is.
Upvotes: 1
Views: 107
Reputation: 5737
Any()
will just check if there's one or more items in a collection which matches a given predicate. Without the predicate (as in your case) it will check if there's at least one item in the collection.
It won't change anything in your collection, however - that's what I think that coworker wanted to achieve - it forces the runtime to evaulate the expression to retrieve the values from the database. As you might know, expressions returning an IEnumerable
or IQueryable
are not executed as long it is not needed to do so. The first call to that expressions which depends on the return values of the expression will force its execution and your coworker might have seen that then the SQL profiler shows incoming statements.
However, I see that the line below calls a ToList()
which also makes sure that the expression is executed immediately. So no, you really should not need that Any()
.
Upvotes: 1