簡體   English   中英

如何在entityFramework中修改記錄列表

[英]How to Modify List of Records in 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的奇怪行為!! 任何解釋???
謝謝!

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

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

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

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

//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"
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM