Does calling ToArray on IQueryable de-attach the entity in LinqToSql? - linq-to-sql

I have a LinqToSql query that returns an array of Article objects like so:
return db.Articles.ToArray();
I then loop over this array and start to delete some items that meet a certain criteria, for simplicity let's say I delete them all, like so:
foreach (var item in array)
db.articles.DeleteOnSubmit(item);
The call to DeleteOnSubmit(entity) throws an invalid operation exception, it's message says "Can not delete an entity that has not been attached". I modified the code to get the entity first then delete it and it worked just fine. Here's the working code:
db.DeleteOnSubmit(db.Articles.Where(c=>c.Id == item.Id))
Now, I know it would work if I modified the repository to return IQueryable instead of a native array, I just don't understand why? Does ToArray has anything to do with this invalid operation exception?
Thanks.
ps: db is a reference to a DataContext object.

I suspect your using different DataContexts when selecting entities and when submitting changes. If this is the case, the error is natural and would still happen if you returned an IQueryable instead of a native array. Either you Attach an entity to the new data context or you use the same where you selected the initial entities.

Can you put it all in one method and try?
The answer is "No", it doesn't.
Unless you are using differen't db for delete than select (could happenw ithout you realize it) or db.ObjectTrackingEnabled is set to false somewhere.

Related

Avoiding race conditions for a custom get_or_create in Django?

Can anyone advise on the following problem:
I have a custom get_or_create method, which checks multiple fields and does some fancy stuff upon creation:
def fancy_get_or_create(name):
object = self.fancy_get(name)
if not object:
object = self.fancy_create(name)
return object
def fancy_get(name):
return self.filter(Q(name=name) | Q(alias=name)).first()
def fancy_create(name):
name = self.some_preprocessing(name)
return self.create(name=name, alias=name)
There's a race condition, where one request will check to see if the object exists, find nothing, and start creating it. Before that request finishes creating the object, another request comes in looking for the same object, finds, nothing, and begins creating the new object. This request will fail because the database has some uniqueness constraints (the previous request had just created the object, so the second request will fail).
Is there any way to prevent request 2 from querying the database until request 1 has finished? I was reading about transaction management and it did not seem like the solution, since the issue is not partial updates (which would suggest an atomic transaction), but rather the need to make the second request wait until the first has finished.
Thanks!
Update:
Here's what I went with:
try:
return self.fancy_get(name) or self.fancy_create(name)
except IntegrityError:
return self.fancy_get(name)
There are two viable solutions:
Use a mutex so only one process can access the fancy_get_or_create
function at the same time.
Capture the error thrown by the database and do something instead: ignore
that create, update the row instead of creating it, throw an
exception, etc.
Edit: another solution might be doing an INSERT IGNORE instead of just an INSERT. https://dev.mysql.com/doc/refman/5.1/en/insert.html

Coldfuson CFScript "setSQL" method was not found

I've got a Coldfusion component, with a method in it called getColumnNames
This just queries a MySQL table, and returns the columnlist:
remote string function getColumnNames() {
qProcessCars = new Query();
qProcessCars.setDataSource('#APPLICATION.dsn#');
qProcessCars.setSQL('SELECT * FROM sand_cars WHERE 1 LIMIT 1');
qProcessCars = qProcessCars.Execute().getResult();
return qProcessCars.columnlist;
}
If I access this remotely in the browser, with page.cfc?method=getColumnNames, then I get the expected list of columns back.
However, if I try to access this from inside another method within the component, I get an error
remote string function otherFunction() {
...
sColumns = getColumnNames();
...
}
The error dump for the above code returns the message "The setSQL method was not found".
So can anyone help me find out why it works as a remote call, but not when called from another method inside the same component.
Problem may be caused some kind of race conditions. If you make few calls which interfere, at some point qProcessCars may already be query result, so invoking method is not possible.
I would try to make the qProcessCars variable local scoped (var qProcessCars = new Query();
) and/or try to use another variable name for query results.
Next possible step is to enclose the query building/executing code into named lock.
Ah I've answered my own question again. Sorry.
I've used the same name qProcessCars else where in the component, I hadn't put var in front of them.
I don't know WHY that was causing the problem, but it was. Maybe setSQL can only be called once per query object?

Linq-to-SQL EntitySet Is Not IQueryable -- Any Workarounds?

When you query an EntitySet property on a model object in Linq-to-SQL, it returns all rows from the entityset and does any further querying client-side.
This is confirmed in a few places online and I've observed the behavior myself. The EntitySet does not implement IQueryable.
What I've had to do is convert code like:
var myChild = ... ;
// Where clause performed client-side.
var query = myChild.Parents().Where(...) ;
to:
var myChild = ... ;
// Where clause performed in DB and only minimal set of rows returned.
var query = MyDataContext.Parents().Where(p => p.Child() == myChild) ;
Does anyone know a better solution?
A secondary question: is this fixed in the Entity Framework?
An EntitySet is just a collection of entities. It implements IEnumerable, not IQueryable. The Active Record pattern specifies that entities be directly responsible for their own persistence. OR mapper entities don't have any direct knowledge of the persistence layer. OR Mappers place this responsibility, along with Unit Of Work, and Identity Map responsibilities into the Data Context. So if you need to query the data source, you gotta use the context (or a Table object). To change this would bend the patterns in use.
I had a similar problem: How can I make this SelectMany use a join. After messing with LINQPad for a good amount of time I found a decent workaround. The key is to push the EntitySet you are looking at inside a SelectMany, Select, Where, etc. Once it's inside that it becomes an Expression and then the provider can turn it into a proper query.
Using your example try this:
var query = from c in Children
where c == myChild
from p in c.Parents
where p.Age > 35
select p;
I'm not able to 100% verify this query as I don't know the rest of your model. But the first two lines of the query cause the rest of it to become an Expression that the provider turns into a join. This does work with my own example that is on the question linked to above.

LINQ to SQL Table Extensibility Methods

If I have a LINQ to SQL table that has a field called say Alias.
There is then a method stub called OnAliasChanging(string value);
What I want to do is to grab the value, check the database whether the value already exists and then set the value to the already entered value.
So I may be changing my alias from "griegs" to "slappy" and if slappy exists then I want to revert to the already existing value of "griegs".
So I have;
partial void OnaliasChanging(string value)
{
string prevValue = this.alias;
this.Changed = true;
}
When I check the value of prevValue it's always null.
How can I get the current value of a field?
Update
If I implement something like;
partial void OnaliasChanging(string value)
{
if (this.alias != null)
this.alias = "TEST VALUE";
}
it goes into an infinte loop which is unhealthy.
If I include a check to see whether alias already == "TEST VALUE" the infinate loop still remains as the value is always the original value.
Is there a way to do this?
The code snippets you've posted don't lend themselves to any plausible explanation of why you'd end up with an infinite loop. I'm thinking that this.alias might be a property, as opposed to a field as the character casing would imply, but would need to see more. If it is a property, then you are invoking the OnAliasChanging method before the property is ever set; therefore, trying to set it again in the same method will always cause an infinite loop. Normally the way to design this scenario is to either implement a Cancel property in your OnXyzChanging EventArgs derivative, or save the old value in the OnXyzChanging method and subsequently perform the check/rollback in the OnXyzChanged method if you can't use the first (better) option.
Fundamentally, though, what you're trying to do is not very good design in general and goes against the principles of Linq to SQL specifically. A Linq to SQL entity is supposed to be a POCO with no awareness of sibling entities or the underlying database at all. To perform a dupe-check on every property change not only requires access to the DataContext or SqlConnection, but also causes what could technically be called a side-effect (opening up a new database connection and/or silently discarding the property change). This kind of design just screams for mysterious crashes down the road.
In fact, your particular scenario is one of the main reasons why the DataContext class was made extensible in the first place. This type of operation belongs in there. Let's say that the entity here is called User with table Users.
partial class MyDataContext
{
public bool ChangeAlias(Guid userID, string newAlias)
{
User userToChange = Users.FirstOrDefault(u => u.ID == userID);
if ((userToChange == null) || Users.Any(u => u.Alias == newAlias))
{
return false;
}
userToChange.Alias = newAlias;
// Optional - remove if consumer will make additional changes
SubmitChanges();
return true;
}
}
This encapsulates the operation you want to perform, but doesn't prevent consumers from changing the Alias property directly. If you can live with this, I would stop right there - you should still have a UNIQUE constraint in your database itself, so this method can simply be documented and used as a safe way to attempt a name-change without risking a constraint violation later on (although there is always some risk - you can still have a race condition unless you put this all into a transaction or stored procedure).
If you absolutely must limit access to the underlying property, one way to do this is to hide the original property and make a read-only wrapper. In the Linq designer, click on the Alias property, and on the property sheet, change the Access to Internal and the Name to AliasInternal (but don't touch the Source!). Finally, create a partial class for the entity (I would do this in the same file as the MyDataContext partial class) and write a read-only wrapper for the property:
partial class User
{
public string Alias
{
get { return AliasInternal; }
}
}
You'll also have to update the Alias references in our ChangeAlias method to AliasInternal.
Be aware that this may break queries that try to filter/group on the new Alias wrapper (I believe Linq will complain that it can't find a SQL mapping). The property itself will work fine as an accessor, but if you need to perform lookups on the Alias then you will likely need another GetUserByAlias helper method in MyDataContext, one which can perform the "real" query on AliasInternal.
Things start to get a little dicey when you decide you want to mess with the data-access logic of Linq in addition to the domain logic, which is why I recommend above that you just leave the Alias property alone and document its usage appropriately. Linq is designed around optimistic concurrency; typically when you need to enforce a UNIQUE constraint in your application, you wait until the changes are actually saved and then handle the constraint violation if it happens. If you want to do it immediately your task becomes harder, which is the reason for this verbosity and general kludginess.
One more time - I'm recommending against the additional step of creating the read-only wrapper; I've put up some code anyway in case your spec requires it for some reason.
Is it getting hung up because OnaliasChanging is firing during initialization, so your backing field (alias) never gets initialized so it is always null?
Without more context, that's what it sounds like to me.

Why am I getting "Invalid Cast" when using Linq to SQL?

I am a bit of a newbie when it comes to Linq to SQL but I hope you can help out. I've written the following Linq to SQL statement with Extension Methods:
Cedb.ClassEvents.Where(c => c.ClassID == 1).Select(c => c).Single()
Where Cedb is the Datacontext, ClassEvents is a table (for classes and events being held at a facility) and ClassID is a unique integer key.
This query runs fine in LinqPad (without Cedb). When it returns, it says that the return type is "ClassEvent". In Intellisense in Visual studio, it tells me that the return type of this query is ClassEvent (created in my data model). However, when I try to place the results in a variable:
var classEvent = Cedc.ClassEvents.Where(c.ClassID == 1).Select(c => c).Single();
then I get an error: InvalidCastException: Specified cast is not valid. The same thing happens if I use the "ClassEvent" class in place of the var. I'm new to this but this one seems like a true slam dunk rather than a bug. Is there something about the Single method that I don't know that is leading to the error? Any help would be appreciated!
Slace - and any other interested parties. The cause of the "Invalid Cast Exception" error was a change in the underlying data model. A smallint field had been changed to bit. Thus, when the system tried to map the query results onto the "ClassEvent" data structure, the conflict between the model (which had not been updated) and the data table emerged.
Nonetheless, I do appreciate the answer!
You don't need to do both a Select and a Single, in fact, you don't even need the Where, you can get away with (see http://msdn.microsoft.com/en-us/library/bb535118.aspx):
var classEvent = Cedc.ClassEvents.Single(c => c.ClassID == 1);
I'd also recommend against using Single unless you're 100% sure that the Func<T, bool> will always return a value, as if it doesn't return a value you will have an exception thrown. Better is using SingleOrDefault and doing a null check before interaction with the object (http://msdn.microsoft.com/en-us/library/bb549274.aspx)