这是我的代码,效果很好。
public async Task<bool> UpdateDeviceShutdownAsync(Guid id, DateTime shutdownAtTime, int areaID, decimal mileage,
decimal motohours, int driverID, List<int> commission,
string shutdownPlaceDescr, int deviceShutdownTypeID, string deviceShutdownDesc,
bool isTransportation, string violationConditions, DateTime shutdownStartTime,
DateTime shutdownEndTime, string notes, List<Guid> faultIDs )
{
try
{
using (var db = new GJobEntities())
{
var isExisting = await db.DeviceShutdowns.FirstOrDefaultAsync(x => x.ID == id);
if (isExisting != null)
{
isExisting.AreaID = areaID;
isExisting.DriverID = driverID;
isExisting.IsTransportation = isTransportation;
isExisting.Mileage = mileage;
isExisting.Motohours = motohours;
isExisting.Notes = notes;
isExisting.DeviceShutdownDesc = deviceShutdownDesc;
isExisting.DeviceShutdownTypeID = deviceShutdownTypeID;
isExisting.ShutdownAtTime = shutdownAtTime;
isExisting.ShutdownEndTime = shutdownEndTime;
isExisting.ShutdownStartTime = shutdownStartTime;
isExisting.ShutdownPlaceDescr = shutdownPlaceDescr;
isExisting.ViolationConditions = violationConditions;
// Delete children
foreach (var existingChild in isExisting.DeviceShutdownFaults.ToList())
{
db.DeviceShutdownFaults.Remove(existingChild);
}
if (faultIDs != null && faultIDs.Any())
{
foreach (var faultItem in faultIDs)
{
var newChild = new DeviceShutdownFault
{
ID = Guid.NewGuid(),
DDFaultID = faultItem,
DeviceShutdownID = isExisting.ID,
};
isExisting.DeviceShutdownFaults.Add(newChild);
}
}
// Delete all children
foreach (var existingChild in isExisting.DeviceShutdownComissions.ToList())
{
db.DeviceShutdownComissions.Remove(existingChild);
}
// Add all new children
if (commission != null && commission.Any())
{
foreach (var cItem in commission)
{
var newChild = new DeviceShutdownComission
{
ID = Guid.NewGuid(),
PersonalID = cItem,
DeviceShutdownID = isExisting.ID,
};
isExisting.DeviceShutdownComissions.Add(newChild);
}
}
await db.SaveChangesAsync();
return true;
}
}
}
catch (Exception ex)
{
logger.Error(ex);
}
return false;
}