2

I have html page with table. When I change field I need to re-save existing record in table.

public int SaveTask(TimesheetListModel task, int userId)
{
    var worklog = new tblWorkLog();

    if (task != null)
    {
        worklog.AccountId = userId;     
        worklog.WorkDate = task.Date;
        worklog.Note = task.Note;       
        worklog.TaskTitle = task.Task;

        DataContext.tblWorkLogs.InsertOnSubmit(worklog);

        DataContext.SubmitChanges(ConflictMode.FailOnFirstConflict);
    }

    return worklog.WorkItemId;
}

This function saves data to table tblWorklogs and returns me id of record. But when I updating record, I already have id of record and I need to find this record in table and update fields. How to do this? I wrote begin function:

public bool UpdateTask(TimesheetListModel task)
{
    /* If update succefull must return true */
    return false;
}

1 Answer 1

3

Not too sure on your implementation but depending on the context you could do something like.

public bool UpdateTask(TimesheetListModel task)
{
    var entity = DataContext.tblWorkLogs.FirstOrDefault(twl => twl.Id == task.Id);
    if (entity != null)
    {
      entity.AccountId = userId;     
      entity.WorkDate = task.Date;
      entity.Note = task.Note;       
      entity.TaskTitle = task.Task;
      DataContext.SubmitChanges();
      return true;
    }

    return false;
}

The logic behind it is:

  • Attempt to retrieve entity from Database.
  • If it exists, edit property/properties as desired
  • Save Changes

This all relies on whether you are tracking entities, otherwise you have to Attach the entity.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.