I am creating a web application, and in this application I want to allow users to update their user information (name, surname, email address, phone number, company name) or change their password. When the page loads, their current information is entered into the text fields. My problem is that I do not know how to apply the changes made by the user. Currently my code is as follows:
DataClasses1DataContext context = new DataClasses1DataContext();
User user = new User();
protected void Page_Load(object sender, EventArgs e)
{
string usr = Session["SessionUserName"].ToString();
user = (from u in context.Users
where u.username.Equals(usr)
select u).FirstOrDefault();
txtFName.Text = user.firstName;
txtLName.Text = user.lastName;
txtCompany.Text = user.companyName;
txtEmail.Text = user.email;
txtPhone.Text = user.phoneNumber;
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
using (DataClasses1DataContext context2 = new DataClasses1DataContext())
{
User nUser = (from u in context2.Users
where u.username == user.username
select u).SingleOrDefault();
if (nUser != null)
{
nUser.firstName = txtFName.Text;
nUser.lastName = txtLName.Text;
nUser.email = txtEmail.Text;
if (!String.IsNullOrEmpty(txtPhone.Text))
nUser.phoneNumber = txtPhone.Text;
if (!String.IsNullOrEmpty(txtCompany.Text))
nUser.companyName = txtCompany.Text;
nUser.timeStamp = DateTime.Now;
}
context2.SubmitChanges();
Response.Redirect("Projects.aspx");
}
This does not give me any errors, but also does not apply the changes. Some searches led me to add
context2.Users.Attach(nUser);
but this gave me the error message: System.InvalidOperationException: Unable to attach an entity that already exists. So I tried
context2.Users.Attach(nUser, true);
and I got the same error message.
google , , 3 ( .Detach context.Users.Detach , ). , ( , ), , "" . , , , . .
EDIT: - , . , .
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string usr = Session["SessionUserName"].ToString();
user = (from u in context.Users
where u.username.Equals(usr)
select u).FirstOrDefault();
txtFName.Text = user.firstName;
txtLName.Text = user.lastName;
txtCompany.Text = user.companyName;
txtEmail.Text = user.email;
txtPhone.Text = user.phoneNumber;
}
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
user.firstName = txtFName.Text;
user.lastName = txtLName.Text;
user.email = txtEmail.Text;
if (!String.IsNullOrEmpty(txtPhone.Text))
user.phoneNumber = txtPhone.Text;
if (!String.IsNullOrEmpty(txtCompany.Text))
user.companyName = txtCompany.Text;
user.timeStamp = DateTime.Now;
context.SubmitChanges();
Response.Redirect("Projects.aspx");
}