SHOAIB
SHOAIB

Reputation: 11

How to update data in Entity Framework?

I have to update data in the data base. Data is shown in text boxes wen i select a data grid-view row. where am i wrong??

private void btnUpdate_Click(object sender, EventArgs e)
{
    ent = new EmployeeEntities();

        EmployeeInfo emp = new EmployeeInfo();
        emp.EmpID = Convert.ToInt32(txtID.Text);
        emp.EmpName = txtName.Text;
        emp.EmpAddress = txtAddress.Text;
        emp.EmpDesignation = txtDesignation.Text;
        //ent.EmployeeInfoes.Add(emp);
        ent.SaveChanges();
        MessageBox.Show("Updated");

}

Upvotes: 1

Views: 122

Answers (3)

elolos
elolos

Reputation: 4450

The entity/ies you wish to save have to be attached to a data context in order to be saved upon calling SaveChanges. If calling ent.SaveChanges() calls the context's SaveChanges() then you only have to use ent.EmployeeInfoes.Add(emp);. If not, you need to retrieve the EmployeeEntities from the database first and then add the EmployInfo.

Upvotes: 2

Ali Baghdadi
Ali Baghdadi

Reputation: 648

if you are trying to add emp as a new emplouee, try

ent.EmployeeInfoes.AddObject(emp);
ent.SaveChanges();

else you must get emp from the list of employees then save it

Upvotes: 0

Cris
Cris

Reputation: 13351

replace

EmployeeInfo emp = new EmployeeInfo();

by

int empId=Convert.ToInt32(txtID.Text);
EmployeeInfo emp =ent.EmployeeInfoes.Single(e=>e.EmpId==empId);

Upvotes: 1

Related Questions