实体框架DbContext更新值,无需查询且通过外键 [英] Entity framework DbContext update value without query and by foreign key
问题描述
我有一种更新某些表的方法。要进行更新,我需要先获取 TestProcess
,但我不喜欢这样。如何在没有 select(firstOrDefault)
操作的情况下更新 TestProcess
,该操作仅用于更新操作?
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?
方法示例:
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();
}
}
推荐答案
TestProcess pr = new TestProcess()
{
MyID == id,
};
context.Set<TestProcess>().Attach(pr);
pr.UpdateID = updateID;
context.SaveChanges();
如果将值设置为该类型的默认值(例如,设置 int
到 0
),则不会将其作为更改,而您需要手动设置状态。
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);
这篇关于实体框架DbContext更新值,无需查询且通过外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!