It seems to me that Linq can only -query- a given data source, that is, it browses through it and returns stuff from it as necessary, but doesn't change anything. However, the wording in some of the answers I found on the matter are making me doubt this understanding. Is my understanding correct in all circumstances? Can a linq query -ever- change the content of the data source it is associated to?
Can a linq query -ever- change the content of the data source it is associated to?
Yes, though this is a bad idea.
LINQ queries (at least with LINQ to Objects) work by using delegates for the filter or mapping operations. In general, these shouldn't ever cause side effects, but that doesn't mean that they couldn't do so if you forced them to. The actual LINQ methods won't change the data, but they work via delegates that are just code you provide, which means that code could do anything.
Note that this would, in general, be a bad idea.
For example, say you were doing a query over a collection of Person instances:
var results = people.Where(p => p.Name == "Foo")
.Select(p =>
{
// This is evil, don't do it!
p.Name = "Bar";
return p;
});
That being said, this is unlikely to work with LINQ against an IQueryable<T>. In that case, the lambda you provide will be converted into an Expression, which will in turn need to be translated by the provider into some other form (ie: Entity Framework converts this to SQL). As such, you would only be able to create side effects if the provider was written in a way that this would translate into a meaningful form, which is unlikely to be the case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With