The next step will be to add the code to allow the user to
create new or update records in the table.
1.
Switch to Design view and double click on the Save button to create the
button click event handler.
2.
Add the following code to the click event handler.
using (OrderDBContainer db = new OrderDBContainer())
{
UserAccount userAccount = new UserAccount();
userAccount.FirstName = txtFirstName.Text;
userAccount.LastName = txtLastName.Text;
userAccount.AuditFields.UpdateDate = DateTime.Now;
if (ddlUsers.SelectedItem.Value == "")
{
//Adding
userAccount.AuditFields.InsertDate = DateTime.Now;
db.UserAccounts.AddObject(userAccount);
}
else
{
//Updating
userAccount.Id = Convert.ToInt32(ddlUsers.SelectedValue);
userAccount.AuditFields.InsertDate = Convert.ToDateTime(lblInserted.Text);
db.UserAccounts.Attach(userAccount);
db.ObjectStateManager.ChangeObjectState(userAccount, System.Data.EntityState.Modified);
}
db.SaveChanges();
lblInserted.Text = userAccount.AuditFields.InsertDate.ToString();
lblUpdated.Text = userAccount.AuditFields.UpdateDate.ToString();
//Reload the drop down list
LoadUserDropDownList();
//Select the one the user just saved.
ddlUsers.Items.FindByValue(userAccount.Id.ToString()).Selected = true;
}
This code starts
by instanciating the OrderDBContainer object and then creates a new instance of
a UserAccount object. The FirstName and LastName are set to the value entered
by the user. The UpdateDate is set to the current date\time. The next line
checks if the selected item in the Users drop down list is blank. A blank
value would signify that the user selected "Create New User". If
they are creating a new user then the InsertDate is set to the current
date\time and the UserAccount object is added to the list of UserAccount
objects associated with the OrderDBContainer. This doesn't add the record to
the database, it simply lets the OrderDBContainer know that this object should
be added to the database.
If the user was
updating a record rather than adding one then the "else" logic would
be followed. The Id is set to the Id of the selected item in the drop down
list. The InsertDate should not be changed so the value that is displayed in
the label for the insert date is used. Since we don't want to add this record
we need to call the Attach method on the UserAccounts object. Again this tells
the OrderDBContainer that this object exists. You then have to tell the
OrderDBContainer to update the record associated with this object. To do that
you call the ObjectStateManager.ChangeObjectState method and pass in the object
to be updated and the Modified entity state enumeration value.
The
db.SaveChanges() method actually executes either the INSERT or UPDATE statement
against the database. Once the record is added or updated then the labels on
the screen are updated to reflect the audit dates and the drop down list is
refreshed. You should be able to run the project now and add a few records.