Update row in entity frmae work
how to update fields in sql server . i am using entity framework my application.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Pranay RanaRank #735 · 3.2K reputationPosted Mar 2, 2015, 8:40 PM EST
1. senario - You are fetching and updating using same context object
In that you can do like this
using (var ctx = new MyDBContext())
var obj = ctx.ObjectLists.FirstOrDefault(o=>o.id==1);
obj.Prop1Value = property value to set;
ctx.SaveChanges();
}
2. Scenario - You are fetching using one context object and updating using another context object
public MyObject GetObject(int id)
{
using (var ctx = new MyDBContext())
{
MyObject obj = ctx.ObjectLists.FirstOrDefault(o=>o.id==1);
}
return obj;
}
public void UpdateObject(Type PropertyValue, MyObject obj)
{
//this line can be out of this method this is just for example
obj.Prop1Value = PropertyValue;
using (var ctx= new MyDBContext())
{
//first attche object
ctx.ObjectList.Attach(obj);
//Second cahnge stat of attached objbect
ctx.ObjectStateManager.ChangeObjectState(obj, System.Data.EntityState.Modified);
//Third save object
ctx.SaveChanges();
}
}
veerendra kumar47 reputationPosted Mar 2, 2015, 9:14 PM EST
i am using first scenario.
i got result..
Suraj SahooRank #382 · 6.6K reputationPosted Mar 2, 2015, 8:27 PM EST
Please follow the below links, I am sure these will help you.
http://www.entityframeworktutorial.net/EntityFramework4.3/update-entity-using-dbcontext.aspx
http://www.entityframeworktutorial.net/update-entity-in-entity-framework.aspx
Accept if helps anyway.
Thanks