我有一个带有ac#code-behind的asp.net应用程序,连接到带有linq-to-entities的SQL数据库...当我尝试对以下代码'SaveChanges()'时,我得到一个异常(列出下面)。什么是关于什么的想法?
private void setNewRide(long newRideID, int carNum)
{
handleCompletedRide(carNum);
using (myEntities = new RamRideOpsEntities())
{
Vehicle assignedCar = myEntities.Vehicles.FirstOrDefault(car => car.CarNum == carNum);
Ride newRide = myEntities.Rides.FirstOrDefault(ride => ride.identity == newRideID);
if (assignedCar != null && newRide != null)
{
vs_CurrentRideId = newRide.identity; //Save current ride to ViewState
vs_CarStatus = assignedCar.Status; //Save old status to ViewState
assignedCar.Status = "EnRoute";
assignedCar.CurrPassengers = newRide.NumPatrons;
assignedCar.StartAdd = newRide.PickupAddress;
assignedCar.EndAdd = newRide.DropoffAddress;
assignedCar.CurrentAdd = newRide.DropoffAddress;
assignedCar.Rides.Add(newRide);
newRide.TimeDispatched = DateTime.Now;
newRide.WaitTime = (((DateTime)newRide.TimeDispatched) - ((DateTime)newRide.TimeOfCall));
newRide.AssignedCar = carNum;
newRide.Status = "EnRoute";
myEntities.SaveChanges(); //EXCEPTION HERE!
SelectCarUP.DataBind();
SelectCarUP.Update();
}
}
}
例外:
UPDATE语句与FOREIGN KEY约束冲突 \ “FK_Rides_Vehicles \”。冲突发生在数据库中 \“CWIS29RamRideOps \”,表\“dbo.Vehicles \”,列 '身份'。\ r \ n声明已被终止。
数据库:
答案 0 :(得分:1)
这一行:
assignedCar.Rides.Add(newRide);
被翻译为SQL-INSERT - 虽然您已经有一个具有相同ID的记录。决定你想做什么:插入一个新的骑行(在这种情况下你应该对newRide的id进行NULL化),或者更新它(在这种情况下你应该只注释掉那行;更改将被保存)。
答案 1 :(得分:0)
更改您的代码:
newRide.TimeDispatched = DateTime.Now;
newRide.WaitTime = (((DateTime)newRide.TimeDispatched) - ((DateTime)newRide.TimeOfCall));
newRide.AssignedCar = carNum;
newRide.Status = "EnRoute";
assignedCar.Status = "EnRoute";
assignedCar.CurrPassengers = newRide.NumPatrons;
assignedCar.StartAdd = newRide.PickupAddress;
assignedCar.EndAdd = newRide.DropoffAddress;
assignedCar.CurrentAdd = newRide.DropoffAddress;
assignedCar.Rides = newRide; // Your First Change here
myEntities.SaveChanges();