[英]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.