tags:

views:

22

answers:

0

This problem drives me crazy.

All I'm trying to do is writing some child record and update the parent with some basic increment. When I submit the changes an ChangeConflictException is thorwn..

Here's the code

using (BizNetDB db = new BizNetDB())
{
    var dbServiceCall = db.ServiceCalls.SingleOrDefault(
        x => x.ServiceCallID == serviceCallDetail.ServiceCallID);

    var dbServiceCallDetail = dbServiceCall.ServiceCallDetaills
        .SingleOrDefault(x => 
        x.ServiceCallDetailID == serviceCallDetail.ServiceCallDetailID);

    if (dbServiceCallDetail == null)
    {
        dbServiceCallDetail = new Data.ServiceCallDetaill();
        dbServiceCall.ServiceCallDetaills.Add(dbServiceCallDetail);
    }

    dbServiceCallDetail.EndSession = serviceCallDetail.EndSession;
    dbServiceCallDetail.ExitTime = serviceCallDetail.ExitTime;
    dbServiceCallDetail.Solution = serviceCallDetail.Solution;
    dbServiceCallDetail.StartSession = serviceCallDetail.StartSession;

    var sessionDuration = 
        serviceCallDetail.EndSession - serviceCallDetail.StartSession;

    serviceCallDetail.SessionMinutes = sessionDuration.Minutes;

    if (serviceCallDetail.ExitTime.HasValue)
    {
        var driveDuration =
            serviceCallDetail.StartSession - serviceCallDetail.ExitTime.Value;

        serviceCallDetail.DriveMinutes = driveDuration.Minutes;
    }
    else
    {
        serviceCallDetail.DriveMinutes = 0;
    }

    var totalMinutes = (
        from d in db.ServiceCallDetaills
        where d.ServiceCallID == serviceCallDetail.ServiceCallID
        where d.ServiceCallDetailID != dbServiceCallDetail.ServiceCallDetailID)
        group d by d.ServiceCallID into g
        select new
        {
            SessionMinutes = g.Sum(x => x.SessionMinutes), 
            DriveMinutes = g.Sum(x => x.DriveMinutes)
        }).First();

    dbServiceCall.SessionMinutes =
        totalMinutes.SessionMinutes + serviceCallDetail.SessionMinutes;

    dbServiceCall.DriveMinutes =
        totalMinutes.DriveMinutes + serviceCallDetail.DriveMinutes;

    try
    {
        db.SubmitChanges();
    }
    catch (ChangeConflictException ex)
    {
        db.ChangeConflicts.ResolveAll(RefreshMode.OverwriteCurrentValues);
        db.SubmitChanges();
    }
}

The second Submit did solve the problem.. but I want to solve it from the root!

when I disabled this lines (The parent changes):

dbServiceCall.SessionMinutes = totalMinutes.SessionMinutes +
    serviceCallDetail.SessionMinutes;
dbServiceCall.DriveMinutes = totalMinutes.DriveMinutes + 
    serviceCallDetail.DriveMinutes;

everithing is Ok.

please help...