Hoody
Hoody

Reputation: 3381

Update foreign key column

I can't figure out how you do this in linq-to-sql.

Simple foreign key example below.

CARS TABLE
Columns - CARID (PK), NAME, SIZE, MODELID(FK)


MODELS TABLE
Columns MODELID(PK), MODELNAME

To change the Model of the car in SQL I would

UPDATE CARS
SET MODELID = 'MODEL88'
WHERE CARID = 'CAR01'

In linq-to-sql I tried to do something similar, but the update doesn't work.

Car car = db.Cars.Where(x => x.CarId == "CAR01").FirstOrDefault();
Model model = db.Models.Single(c => c.ModelId == "MODEL88");
car.Model = model;
db.SubmitChanges();

There are no exceptions, it just doesn't do the update. Updating other fields which are not foreign keys does work e.g. size.

Car car = db.Cars.Where(x => x.CarId == "CAR01").FirstOrDefault();
car.Size = "22";
db.SubmitChanges();

Upvotes: 1

Views: 1808

Answers (2)

Richard
Richard

Reputation: 8280

Hmm, bizarre. Are the relationships set-up in the database? and is this reflected in your .DBML?

Out of curiousity, does it work if you add car to the Cars colleciton on model, like so:

Car car = db.Cars.Where(x => x.CarId == "CAR01").FirstOrDefault();
Model model = db.Models.Single(c => c.ModelId == "MODEL88");
model.Cars.Add(car)
db.SubmitChanges();

Upvotes: 1

Mediator
Mediator

Reputation: 15378

maybe it will work:

Car car = db.Cars.Where(x => x.CarId == "CAR01").FirstOrDefault();
Model model = db.Models.Single(c => c.ModelId == "MODEL88");
car.ModelId = model.Id;
db.SubmitChanges();

Upvotes: 0

Related Questions