实体框架DbContext更新值无需查询和外键

zra*_*zdn 4 c# updates dbcontext entity-framework-5

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();
               }
}
Run Code Online (Sandbox Code Playgroud)

use*_*702 6

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

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

pr.UpdateID = updateID;

context.SaveChanges();
Run Code Online (Sandbox Code Playgroud)

如果要将值设置为该类型的默认值(例如,设置int0),则不会将其作为更改进行拾取,您需要手动设置状态.

pr.UpdateID = updateID;
context.Entry(pr).Property(p => p.UpdateID).IsModified = true;
Run Code Online (Sandbox Code Playgroud)

你可以把这些代码放在扩展方法中,这样你就可以做这样的事情(我将把实现留作练习):

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

this.DbContext.UpdateProperty(entity, item => item.Name, model.Name);
Run Code Online (Sandbox Code Playgroud)