tags:

views:

68

answers:

2

Hi,

I am trying to do an update with linq using an explict cast and the changes arent submitting.

Here is the code

Image update = db.Images.Where(i => i.ImageId == imageWithChanges.ImageId).SingleOrDefault();

update = (Image)imageWithChanges;

db.SubmitChanges();

I have an explicit operator in my image class. Can anyone help?

Thanks

+1  A: 

The line

update = (Image)imageWithChanges;

is not changing anything. It's merely swapping the thing the variable update points at. If you want to actually change the image, you'd probably have to copy each property from imageWithChanges to update.

Another way you can do this, is to attach imageWithChanges to db.Images and say it was a modified instance:

db.Images.Attach((Image)imageWithChanges, true); // true means "it's modified"
db.SaveChanges();
Ruben
Thanks Ruben, but when I add the attach it gives me the error "An entity can only be attached as modified without original state if it declares a version member or does not have an update check policy."
Paddy
Thanks or your help guys, I got it fixed.
Paddy
A: 

You say you got it fixed, but don't tell How.

For all others that will read this, I agree with Ruben, you have to Attach it. The error it gives you is valid, you have to either handle concurrency checking (with timestamp or version number) or let last in wins (by setting UpdateCheck to false for all your entity's properties).

devMomentum
sorry, thought I had this fixed. Here is my code Image updatedImage = (Image)image; using (OrebroDataContext db = new OrebroDataContext()) { db.Images.Attach(updatedImage, true); db.Products.AttachAll(updatedImage.Products,true); db.SubmitChanges(); }I have products hanging off my image object, but I keep getting a key in use error. Any ideas?
Paddy
Folks, I have definitely got it fixed. The problem was I had forgot to add a timestamp column to one of my database tables. Once I did that everything worked. Doh. Cheers for everyones help
Paddy