开发者

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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜