silent fail when updating a row via linq to sql
I have some C# code that looks like the following sample:
foreach (car c in listOfCars) {
c.garage.last_opened_at = DateTime.Now;
}
db.SubmitChanges();
Basically, cars
and garages
are in a one-to-one relationship (a somewhat flawed example, I know), and I'm updating the time each garage was last opened.
When I check the database, though, the last_opened_at
field isn't being updated (no error messages are being displayed). Any suggestions why? I looked around SO and on Google, and the solutions I saw all mentioned that garage
needs to have a primary key.开发者_如何学JAVA But I double-checked, and my garage
table is indeed using its foreign key to its associated car as a primary key.
Is the problem that the primary key is also doubling as a foreign key (i.e., do I need a dedicated primary key column)?
There are few possibilities here: last_opened_at
is specified as a database supplied field, you do not have a primary key listed on your linq to sql class and less likely, your listOfCars
does not come from the same db context.
If you marked the field as generated by database, a typical scenario when using timestamps or fields with database defaults, then linq to sql will never attempt to write that property.
If you do not have a primary key on the linq to sql class, regardless of what the database is doing, it will not write to the table. Having the primary key also be a foreign key should not be a problem as long as it is the primary. I ran into this once and thought I remembered an error in this case, but I'm not 100% sure.
If you generate the listOfCars
from one data context, and try to save them on another data context, the second data context has no idea those entities even exist. You can solve this by ensuring you are using the same data context or attaching the entities to the new context.
What if you move the call to SubmitChanges
inside your loop?
foreach (car c in listOfCars) {
c.garage.last_opened_at = DateTime.Now;
db.SubmitChanges();
}
You're missing a call to actually update the models. I believe your example should look like this:
foreach(car c in listOfCars) {
c.garage.last_opened_at = DateTime.Now;
}
db.AcceptAllChanges();
db.SubmitChanges();
Also, updates will never silently fail. If the update fails, it'll throw an UpdateException. What's happening in your case is that your code is going to update but sees no updates accepted in the models and therefore doesn't update anything. If you had a problem with primary or foreign key constraints, you'd get an exception.
精彩评论