[英]FOREIGN_KEY constraint exception
I have an asp.net application with ac# code-behind, connected to an SQL db with linq-to-entities... When I attempt to 'SaveChanges()' on the following code I get an exception (listed below). 我有一个带ac#代码的asp.net应用程序,并使用linq-to-entities连接到SQL数据库...当我尝试对以下代码进行“ SaveChanges()”时,出现异常(在下面列出)。 Any thoughts on what is up? 有什么想法吗?
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();
}
}
}
THE EXCEPTION: 例外情况:
The UPDATE statement conflicted with the FOREIGN KEY constraint \\"FK_Rides_Vehicles\\". UPDATE语句与FOREIGN KEY约束\\“ FK_Rides_Vehicles \\”冲突。 The conflict occurred in database \\"CWIS29RamRideOps\\", table \\"dbo.Vehicles\\", column 'Identity'.\\r\\nThe statement has been terminated. 在数据库\\“ CWIS29RamRideOps \\”,表\\“ dbo.Vehicles \\”,“ Identity”列中发生了冲突。\\ r \\ n该语句已终止。
THE DB: 数据库:
This line: 这行:
assignedCar.Rides.Add(newRide);
is translated as SQL-INSERT - while you already have a record with the same ID. 被转换为SQL-INSERT-当您已经具有相同ID的记录时。 Decide what you want to do: insert a new ride (in which case you should NULLify the id of newRide), or update it (in which case you should just comment that line out; changes will be saved). 确定您要执行的操作:插入新游乐设施(在这种情况下,您应该将newRide的ID设为NULL)或更新(在这种情况下,您应该只注释掉该行;更改将被保存)。
Change your code like this: 像这样更改代码:
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.