在foreach循环中添加或更新实体需要太长时间才能调用SaveChanges()? [英] Adding to or updating an entity in a foreach loop takes too long time before calling SaveChanges()?
问题描述
我有这种方法可以保存带有相关项(多对多关系)的实体,
I have this method that saves an entity with its related items (many-to-many relationship),
private static void Save<T>(TbCommonHistoryLog log, List<T> lstDetails) where T : IHasSerial
{
foreach (var item in lstDetails.OrderBy(x => x.Serial))
{
var ser = SerializeObject(item);
var record = oContext.TbHistoryLog_Lists.FirstOrDefault(x => x.ListObjectJson == ser);
if (record == null) //add new list item
{
TbCommonHistoryLog_Lists listObject = new TbCommonHistoryLog_Lists()
{
ListObjectJson = SerializeObject(item)
};
var details = new TbCommonHistoryLogDetails { TbHistoryLog = log, TbHistoryLog_Lists = listObject };
oContext.TbHistoryLogDetails.Add(details);
}
else //attach an existing list item
{
var o = oContext.TbHistoryLog_Lists.Find(record.Id);
oContext.TbHistoryLog_Lists.Attach(o);
var details = new TbCommonHistoryLogDetails { TbHistoryLog = log, TbHistoryLog_Lists = o };
oContext.TbHistoryLogDetails.Add(details);
}
}
oContext.BulkSaveChanges();
}
我有两个表: TbCommonHistoryLog
, TbCommonHistoryLog_Lists
,它们之间存在多对多关系,联接表为 TbCommonHistoryLogDetails
,
我在这里所做的是对主从模型的审计,所有审计都在数据库中序列化为JSON,我将head对象保存在 TbCommonHistoryLog
表中,并保存每个列表 TbHistoryLog_Lists
表中的项目,在上面的方法中,我检查列表项是否已存在于数据库中或避免重复。
,但是此过程耗时超过15秒,这是一个很长的时间,我无法弄清楚我在做什么错..请帮助?
I have two tables: TbCommonHistoryLog
, TbCommonHistoryLog_Lists
, that are in many to many relationship, the joining table is TbCommonHistoryLogDetails
,
What I'm doing here is an auditing for master-detail models, all audits are serialized to JSON in DB, I save the head object in the TbCommonHistoryLog
table, and every list item in the TbHistoryLog_Lists
table, in the mthod above I check if the list item is already exists in the database or not to avoid duplicating.
but this process takes more than 15 seconds which is a very long time, I can't figure out what am I doing wrong here.. please help?
推荐答案
对于集合中的每个项目,您都在查询数据库。我的建议是将记录保存到var中,然后询问该变量是否在数据库中。
For every single item in collection you're querying database. My suggestion is to save records in var, then ask the variable if the item is in database.
var databaseRecords = oContext.TbHistoryLog_Lists.ToList();
然后在循环中:
var record = databaseRecords.FirstOrDefault(x => x.ListObjectJson == ser);
这篇关于在foreach循环中添加或更新实体需要太长时间才能调用SaveChanges()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!