LINQDataSource / FormView - automatically updating child records
am 04.04.2008 13:27:00 von JayPondyI have a CheckBoxList control on a FormView.
Each item in the CheckBoxList control is a child record of the parent
displayed in the formview.
I am trying to update the child records of the parent in the LINQDataSource
Updating Event as follows:
protected void dsNearMissIncident_Updating(object sender,
LinqDataSourceUpdateEventArgs e)
{
// Get the Parent Record
var oIncident = (Incident)e.NewObject;
// Each item in the checkboxlist is a child of the parent
CheckBoxList chkStates = (CheckBoxList)fv.FindControl("chkStates");
// Loop through the CheckBoxList items and figure out which ones need to
be added/removed as children
foreach (ListItem oItem in chkStates.Items)
{
var oState = new NearMissSafeStartState { StatePKID =
int.Parse(oItem.Value), IncidentPKID = oIncident.PKID };
// Item is selected and not present - add it
if (oItem.Selected &&
!oIncident.NearMissSafeStartStates.Contains(oState))
oIncident.NearMissSafeStartStates.Add(oState);
// Item is de-selected and is present - remove it
else if (!oItem.Selected &&
oIncident.NearMissSafeStartStates.Contains(oState))
oIncident.NearMissSafeStartStates.Remove(oState);
}
}
What I would expect to see is the LINQDataSource automatically update the
child records but it does not, only the parent sees any changes - it's as if
the child records are not even there.
If I hand code creating a new parent and adding children as follows the
children ARE automatically updated:
NearMissDataContext dc = new NearMissDataContext();
Incident oIncident = new Incident { DepartmentPKID = 28, Description =
"Description", InjuryPotentialPKID = 1, Occurred = System.DateTime.Now,
SubmittedByPKID = 1169, SupervisorPKID = 1169, TOPReviewerPKID = 1169 };
oIncident.NearMissSafeStartErrors.AddRange(new NearMissSafeStartError[] {
new NearMissSafeStartError { ErrorPKID = 1 } ,
new NearMissSafeStartError { ErrorPKID = 2 },
new NearMissSafeStartError { ErrorPKID = 3 },
new NearMissSafeStartError { ErrorPKID = 4 }});
oIncident.NearMissSafeStartStates.AddRange(new NearMissSafeStartState[] {
new NearMissSafeStartState { StatePKID = 1 },
new NearMissSafeStartState { StatePKID = 2 },
new NearMissSafeStartState { StatePKID = 3 },
new NearMissSafeStartState { StatePKID = 4 }});
dc.Incidents.InsertOnSubmit(oIncident);
try
{
dc.SubmitChanges();
}
catch (Exception ex)
{
txtMessage.InnerText = ex.Message;
}
In terms of Best Practices how/when should children records be updated using
the LINQDataSource and FormView controls?