我是新來的asp.net,C#和SQL,可以使用一些指導..我使用:下面:數據庫與linq實體框架。我需要將特定的「乘車」與特定的「車輛」相關聯,但我不確定如何繼續。我已經在兩個物體之間設置了導航屬性,但是現在需要讓車輛持有對其所乘坐的列表的引用。我需要一個單獨的車輛列來保存這個列表嗎?有人可以告訴我完成這個的語法嗎?LINQ to Entities外鍵協會
這裏是我目前擁有的代碼,並在兩個點意見,我需要幫助:
private void setNewRide(Ride newRide, int carNum)
{
using (myEntities = new RamRideOpsEntities())
{
var assignedCar = (from car in myEntities.Vehicles
where (car.CarNum == carNum)
select car).FirstOrDefault();
if (assignedCar != null && newRide != null)
{
Ride lastRide = assignedCar.Rides.LastOrDefault(); //HERE IS WHERE I NEED TO LOAD THE MOST RECENT 'RIDE' FOR THIS CAR, IS THIS CORRECT???
if (lastRide != null)
{
lastRide.Status = "Completed";
assignedCar.numRides = assignedCar.numRides + 1;
lastRide.TimeDroppedOff = DateTime.Now;
TimeSpan duration = (lastRide.TimeDroppedOff - lastRide.TimeDispatched).Value;
lastRide.ServiceTime = duration;
if (assignedCar.AvgRideTime == null)
{
assignedCar.AvgRideTime = duration;
}
else
{
assignedCar.AvgRideTime = TimeSpan.FromSeconds((((TimeSpan)assignedCar.AvgRideTime).Seconds + duration.Seconds)/assignedCar.numRides);
}
}
assignedCar.Status = "EnRoute";
assignedCar.CurrPassengers = newRide.NumPatrons;
assignedCar.StartAdd = newRide.PickupAddress;
assignedCar.EndAdd = newRide.DropoffAddress;
//HERE IS WHERE I NEED TO ADD THE 'newRide' OBJECT TO THE LIST OF RIDES IN THE 'assignedCar' ..SYNTAX???
newRide.TimeDispatched = DateTime.Now;
newRide.AssignedCar = carNum;
newRide.Status = "EnRoute";
myEntities.SaveChanges();
SelectCarUP.DataBind();
SelectCarUP.Update();
}
}
}
除非EF做事情聰明我沒有意識到,你所說的問題依賴於SQL Server中不存在的神祕的自然排序(至少以最相信的形式)。這些Rides的順序是基於頁面Sql服務器插入記錄的,如果您知道頁面上剩餘的空間並插入行的確切大小,則該記錄只有確定性。這不太可能,所以使用'OrderBy'子句。回到原來的問題,您評論的代碼行有什麼問題?例外?沒有返回? – Smudge202