更新外键列

时间:2012-04-25 09:58:02

标签: c# linq-to-sql

我无法弄清楚如何在linq-to-sql中执行此操作。

下面简单的外键示例。

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


MODELS TABLE
Columns MODELID(PK), MODELNAME

要在SQL中更改汽车模型,我会

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

在linq-to-sql中我尝试做类似的事情,但更新不起作用。

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

没有例外,它只是不做更新。更新非外键的其他字段确实有效,例如大小

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

2 个答案:

答案 0 :(得分:1)

嗯,很奇怪。是否在数据库中设置了关系?这是否反映在你的.DBML中?

出于好奇,如果您将car添加到Cars上的model收藏中,它是否有效,如下所示:

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();

答案 1 :(得分:0)

也许它会起作用:

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();