![](/img/trans.png)
[英]Entity framework update foreign key to null without query and without id of the related entity
[英]Entity framework DbContext update value without query and by foreign key
我有一個更新一些表的方法。 對於更新,我需要首先獲得TestProcess
,但我不喜歡它。 如何在沒有select(firstOrDefault)
操作的情況下更新TestProcess
,僅用於更新操作?
方法示例:
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
),則不會將其作為更改進行拾取,您需要手動設置狀態。
pr.UpdateID = updateID;
context.Entry(pr).Property(p => p.UpdateID).IsModified = true;
你可以把這些代碼放在擴展方法中,這樣你就可以做這樣的事情(我將把實現留作練習):
Foo entity = this.DbContext.GetEntityForUpdate<Foo>(
item => item.ID, model.ID
);
this.DbContext.UpdateProperty(entity, item => item.Name, model.Name);
您可以這樣做(您可能應該擁有所有測試過程數據):
TestProcess pr = new TestProcess();
pr.Id = id;
pr.UpdateID = updateID;
context.Attach(pr);
context.ObjectStateManager.ChangeObjectState(pr, EntityState.Modified);
context.SaveChanges();
編碼:
TestProcess testprocess = dbcontext.TestProcesses.Attach(new TestProcess { MyID = id });
tp.UpdateID = updateID;
dbcontext.Entry<TestProcess>(testprocess).Property(tp => tp.UpdateID).IsModified = true;
dbcontext.Configuration.ValidateOnSaveEnabled = false;
dbcontext.SaveChanges();
結果TSQL:
exec sp_executesql N'UPDATE [dbo].[TestProcesses]
SET [UpdateID] = @0
WHERE ([MyID] = @1)
',N'@0 bigint,@1 bigint',@0=2,@1=1
注意:
需要“IsModified = true”行,因為在創建新的TestProcess對象時(僅填充了MyID屬性),所有其他屬性都具有其默認值(0,null等)。 如果要使用“默認值”更新數據庫,實體框架將不會檢測到更改,然后不會更新數據庫。
例如:
testprocess.UpdateID = null;
如果沒有“IsModified = true”這一行將無法工作,因為屬性UpdateID在創建空的TestProcess對象時已經為空,您需要向EF說這個列必須更新,這就是這一行的目的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.