开发者

Issue with AttachTo method

开发者 https://www.devze.com 2023-03-26 16:45 出处:网络
For updating record in Entity framework I am trying that. I am just assigningprimary key CompanyID and开发者_运维问答 The name of Company CompanyName to company because I need to change company name o

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

精彩评论

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