updating a record with entity framework not working
This is my code:
...
Domain.Box updatedBox = entities.Boxes.FirstOrDefault(TextBoxBoxID.Text);
updatedBox = getBoxInfo();
entities.SaveChanges();
private Domain.Box getBoxInfo()
{
Domain.Box retBox = new Domain.Box();
retBox.BoxID = TextBo开发者_如何学CxBoxID.Text;
retBox.LocationID = Convert.ToDecimal(TextBoxLocationID.Text);
retBox.Positions = Convert.ToByte(TextBoxPositions.Text);
retBox.DiseaseID = RadComboBoxDisease.SelectedValue;
retBox.SampleTypeID = RadComboBoxSampleType.SelectedValue;
retBox.TubeTypeId = RadComboBoxTubeTypeID.SelectedValue;
return retBox;
}
The code compiles and executes fine, but the database does not changes, this is, all the information is exactly the same as it was before the update. Any help will be appreciated, thanks!
If you want to insert a new Domain.Box object, you should do it like this:
entities.Boxes.AddObject(getBoxInfo());
entities.SaveChanges();
There is no need to create the updatedBox
object because you're just overwriting it. If I understand you're requirements, you want to perform an insert, not an update.
If I'm incorrect and you're trying to update certain properties of the updatedBox
object, then just pass a reference to the object and update it's properties:
Domain.Box updatedBox = entities.Boxes.FirstOrDefault(TextBoxBoxID.Text);
getBoxInfo(ref updatedBox);
entities.SaveChanges();
private void getBoxInfo(ref Domain.Box retBox)
{
retBox.BoxID = TextBoxBoxID.Text;
...
}
entities.SaveChanges();
I think you want to do this:
Domain.Box updatedBox = entities.Boxes.FirstOrDefault(TextBoxBoxID.Text);
UpdateBoxInfo(updatedBox);
entities.SaveChanges();
private void UpdateBoxInfo(Domain.Box theBox)
{
theBox.BoxID = TextBoxBoxID.Text;
theBox.LocationID = Convert.ToDecimal(TextBoxLocationID.Text);
theBox.Positions = Convert.ToByte(TextBoxPositions.Text);
theBox.DiseaseID = RadComboBoxDisease.SelectedValue;
theBox.SampleTypeID = RadComboBoxSampleType.SelectedValue;
theBox.TubeTypeId = RadComboBoxTubeTypeID.SelectedValue;
}
I'd try it this way:
Domain.Box updatedBox = entities.Boxes.FirstOrDefault(TextBoxBoxID.Text);
getBoxInfo(updatedBox);
entities.SaveChanges();
private void getBoxInfo(Domain.Box retBox)
{
retBox.LocationID = Convert.ToDecimal(TextBoxLocationID.Text);
retBox.Positions = Convert.ToByte(TextBoxPositions.Text);
retBox.DiseaseID = RadComboBoxDisease.SelectedValue;
retBox.SampleTypeID = RadComboBoxSampleType.SelectedValue;
retBox.TubeTypeId = RadComboBoxTubeTypeID.SelectedValue;
}
精彩评论