Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity framework DbContext update value without query and by foreign key

I have a method for updating some tables. For update I need get first of TestProcess, but I don't like that. How can I update TestProcess without select(firstOrDefault) operation, used only for the update operation?

Example of method:

public void UpdateTestProcess(int id, string updateID)
{
    using (TestEntities context = new TestEntities())
                {
                    TestProcess pr = context.TestProcess.FirstOrDefault(x => x.MyID == id);
                    pr.UpdateID = updateID;             

                    context.TestProcess.Attach(pr);
                    context.ObjectStateManager.ChangeObjectState(pr, EntityState.Modified);
                    context.SaveChanges();
               }
}
like image 354
zrabzdn Avatar asked Dec 26 '22 00:12

zrabzdn


1 Answers

TestProcess pr = new TestProcess()
{
    MyID == id,
};

context.Set<TestProcess>().Attach(pr);

pr.UpdateID = updateID;

context.SaveChanges();

If you are setting the value to the default value of that type (for example, setting an int to 0) it won't be picked up as a change, and you need to manually set the state.

pr.UpdateID = updateID;
context.Entry(pr).Property(p => p.UpdateID).IsModified = true;

You can put such code away in extension methods, so you can do things like this (I'll leave the implementation as an exercise):

Foo entity = this.DbContext.GetEntityForUpdate<Foo>(
    item => item.ID, model.ID
    );

this.DbContext.UpdateProperty(entity, item => item.Name, model.Name);
like image 100
user247702 Avatar answered Apr 27 '23 05:04

user247702