Govind Malviya
Govind Malviya

Reputation: 13753

Issue with AttachTo method

For updating record in Entity framework I am trying that. I am just assigning primary key CompanyID and The name of Company CompanyName to company because I need to change company name only. Record is not updating.

using (var myentity= new MyEntities())
{
    myentity.AttachTo("Companies", company);
    myentity.SaveChanges();
}

Upvotes: 0

Views: 151

Answers (2)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364299

It is not enough. If you assigned CompanyName before attaching the company you must tell EF that it has changed. Otherwise you must assign it after the company was attached so the EF can track the change for you as (@Daniel described);

using (var myentity= new MyEntities())
{
    myentity.AttachTo("Companies", company);
    ObjectStateEntry entry = myentity.ObjectStateManager.GetObjectStateEntry(company);
    entry.SetModifiedProperty("CompanyName"); 
    myentity.SaveChanges();
}

Upvotes: 1

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174329

I think you need to first attach it and only after that set the company name.

Something like this:

var company = new Company;
company.CompanyID = yourID;

using (var myentity= new MyEntities())
{
    myentity.AttachTo("Companies", company);
    company.CompanyName = newName;
    myentity.SaveChanges();
}

Upvotes: 2

Related Questions