[英]How to add the current row from a list to a DbSet
我正在尝试迭代列表中的每一行,如果列表中的当前行在数据库中还没有记录,则添加当前行,否则继续下一次迭代。 如何将列表中的当前行添加到我的 DbSet。
list.ForEach(x =>
{
objInsuredList = (from obj in _db.dbLifeData
where (obj.identifier == x.identifier) && (obj.plan == x.plan) && (obj.policyno == x.policyno)
select obj).ToList(); //get all existing record
var query = _db.dbLifeData.FirstOrDefault(y => y.identifier == x.identifier
&& y.policyno == x.policyno && y.plan == x.plan); //check current in list if it exists
if(query != null)
{
query.status = x.status;
_db.Entry(query).State = EntityState.Modified;
_db.SaveChanges();
}
else //current row has no record yet in the dbLifeData database
{
}
});
在 EF Core 中,您必须知道您的实体,然后您需要以下代码:
DbSet<Object>().Add(query);
efDataContext.SaveChanges();
我建议改进你的代码,否则你会有很大的性能问题。
将FilterByItems帮助程序扩展复制到您的代码库
// get existing items in one DB roundtrip
var existing = _db.dbLifeData
.FilterByItems(list, (obj, x) => (obj.identifier == x.identifier) && (obj.plan == x.plan) && (obj.policyno == x.policyno), true)
.AsEnumerable()
.ToDictionary(x => (x.identifier, x.plan, x.policyno));
foreach(var x in list)
{
var key = (x.identifier, x.plan, x.policyno);
if (existing.TryGetValue(key, out var found))
{
// EF Core smart enough to detect changes in properties
found.status = status;
}
else
{
var newRecord = new dbLifeData
{
status = x.status,
identifier = x.identifier,
plan = x.plan,
policyno = x.policyno
};
_db.dbLifeData.Add(newRecord);
}
}
// save everything in one batch
_db.SaveChanges();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.