3 回答
TA貢獻1853條經驗 獲得超9個贊
克隆實體的一種廉價的簡便方法是執行以下操作:
var originalEntity = Context.MySet.AsNoTracking()
.FirstOrDefault(e => e.Id == 1);
Context.MySet.Add(originalEntity);
Context.SaveChanges();
這里的訣竅是AsNoTracking() -當您加載這樣的實體時,您的上下文不知道它,并且當您調用SaveChanges時,它將像對待新實體一樣對待它。
如果MySet有引用MyProperty并且您也想要它的副本,則只需使用Include:
var originalEntity = Context.MySet.Include("MyProperty")
.AsNoTracking()
.FirstOrDefault(e => e.Id == 1);
TA貢獻1788條經驗 獲得超4個贊
這是另一個選擇。
在某些情況下,我更喜歡它,因為它不需要您專門運行查詢來獲取要克隆的數據。您可以使用此方法創建已經從數據庫獲得的實體的克隆。
//Get entity to be cloned
var source = Context.ExampleRows.FirstOrDefault();
//Create and add clone object to context before setting its values
var clone = new ExampleRow();
Context.ExampleRows.Add(clone);
//Copy values from source to clone
var sourceValues = Context.Entry(source).CurrentValues;
Context.Entry(clone).CurrentValues.SetValues(sourceValues);
//Change values of the copied entity
clone.ExampleProperty = "New Value";
//Insert clone with changes into database
Context.SaveChanges();
此方法將當前值從源復制到已添加的新行。
添加回答
舉報
