如何修改entityFramework中的记录列表

本文关键字:记录 列表 entityFramework 何修改 修改 | 更新日期: 2023-09-27 18:08:03

使用实体框架,我需要检索实体列表,然后根据一些条件操作该列表,然后将最终列表保存到上下文。
这样的:

    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的奇怪行为!!任何解释? ?
谢谢!

如何修改entityFramework中的记录列表

嗯,根据你的脚本,应该是这样做的。

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

让我先回答为什么没有保存新记录这个简单的问题。您不能只修改对象并调用保存更改,您需要添加或更新数据库。

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

用于修改列表并将其保存到上下文。我相信您将不得不迭代列表本身,并添加,删除,更新其中的每个样本对象。