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();
}
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();
}
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();
}
精彩评论