2015-08-16 56 views
0

使用實體框架,我需要Retreive實體列表,然後根據一些Conitions操縱此列表,然後將最終列表保存到上下文。
這樣的:
如何修改entityFramework中的記錄列表

Sample 
    { 
     int id; 
     int value; 
    } 
var sampleList=db.samples.toList(); 
//Add some records to sampleList 
sampleList.Add(new sample(){value = 10}); 
//Change the Value of Some Records in sampleList 
sampleList[0].value= 5 ; 
db.savechanges() 

添加的記錄到列表是不被跟蹤,並插入到數據庫,但更改後的值更新。
EF的奇怪行爲!任何解釋?
謝謝!

+0

你也可以顯示你的添加到列表的代碼嗎? –

+0

沒有保存,因爲您沒有添加任何內容。您缺少db.samples.add(「樣本對象」),它會通知更改跟蹤器將其添加到您的上下文中。然後db.savechanges()將其保存到數據庫中。 –

回答

0

讓我先回答一個更簡單的問題,即爲什麼你的新記錄沒有保存。您不能只修改對象並調用保存更改,您需要添加或更新數據庫。

db.Add(sample); // If sample does not exist 
db.Update(sample); //If sample already exists and you are updating it 
db.SaveChanges(); 

至於修改列表並將其保存到上下文。我相信你將不得不遍歷列表本身,並添加,刪除,更新其中的每個示例對象。

+0

當然我不想直接向上下文添加記錄,因爲我不知道哪個記錄是新的,應該添加,哪一個應該更新,我們也可以更新值的情況下,問題是與添加。 – Hamed

+0

如果你不能自己弄清楚哪些是新的,你認爲EF能做到這一點嗎?通常很簡單的方法是查看Id是否已設置。 除此之外,如果您可以將項目添加到普通列表並且可以保存,則無法工作。那會造成混亂。 –

+0

因爲所有的工作都是在一個函數內完成的,而且我不希望函數本身訪問DbContext,但似乎沒有其他選擇 – Hamed

0

嗯,根據你的腳本,應該做的是這樣的。

//var sampleList=db.samples.toList(); 
//Add some records to sampleList 
Sample sampInsertObject = new sample() { value = 10 }; 
db.samples.Add(sampInsertObject); 
db.SaveChanges(); // execute save so that context will execute "INSERT" 

/* 
EF also executes SCOPE_IDENTITY() after insert to retrieve the 
PrimaryKey value from the database to sampInsertObject. 
*/ 

// Change the Value of Some Records in sampleList 

var sampUpdateList = db.samples.ToList(); 
if(sampUpdateList.Count != 0) 
{ 
    // Get specific object from sample list 
    Sample sampUpdateObject = sampUpdateList.ToList()[0]; 
    sampUpdateObject.Value = 5; 
    db.SaveChanges(); // execute save so that context will execute "UPDATE" 
}