gpt4 book ai didi

c# - LINQ to Entities 外键关联

转载 作者:太空宇宙 更新时间:2023-11-03 20:28:26 25 4
gpt4 key购买 nike

我是 asp.net、C# 和 sql 的新手,需要一些指导。我正在使用 :below: db 和 linq-to-entities 框架。我需要将特定的“乘车”与特定的“车辆”相关联,但不确定具体如何进行。我已经在两个对象之间设置了一个导航属性,但现在需要让车辆保存对它所乘坐的游乐设施列表的引用。我是否需要在 vehicle 中单独一列来保存此游乐设施列表?有人可以告诉我完成此操作的语法吗?

这是我目前的代码,在我需要帮助的两个地方有注释:

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

EDMX

最佳答案

对于:

// HERE IS WHERE I NEED TO LOAD THE MOST RECENT 'RIDE' FOR THIS CAR, IS 
// THIS CORRECT???
Ride lastRide = assignedCar.Rides.LastOrDefault();

使用:

Ride lastRide = assignedCar.Rides
.OrderByDescending(r => r.TimeDispatched)
.FirstOrDefault();

...以及:

// HERE IS WHERE I NEED TO ADD THE 'newRide' OBJECT TO THE LIST OF RIDES 
// IN THE 'assignedCar' ..SYNTAX???

...根据您的模型图,您的 Vehicle 实体已经有一个 Rides 集合属性,因此您应该能够说:

assignedCar.Rides.Add(newRide);

最后 - 纯粹是个人品味问题 - 而不是:

var assignedCar = (from car in myEntities.Vehicles
where (car.CarNum == carNum)
select car).FirstOrDefault();

我会使用:

var assignedCar = myEntities.Vehicles
.FirstOrDefault(car => car.CarNum == carNum);

关于c# - LINQ to Entities 外键关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9025154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com