我无法弄清楚如何在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();
答案 0 :(得分:1)
出于好奇,如果您将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();