在循环内将数据插入数据库时​​,有没有一种方法可以使foreach循环更快?

问题描述

我正在foreach循环中为每个成员的数据库插入消息,这会使应用程序变慢,因为它将运行200次以上以为每个成员添加消息。我试图使其平行于foreach循环,但是在保存数据时会引发连接错误,而且我有多个foreach循环。

有人在这里帮忙吗?

foreach (var item in coachee)
    {
        MessageRecord MsgRecord = new MessageRecord();
        MsgRecord.MessageID = msgID;
        MsgRecord.CoachID = coachID;
        MsgRecord.CoacheeID = item.CoacheeIdentityID;
        MsgRecord.CreatedBy = Session["user"].ToString();
        MsgRecord.IsActive = 1;
        MsgRecord.CreatedDate = DateTime.Now;
        message.DocumentPath = DocumentPath;

        bool val = await _repoObjCoach.AddMessageRecordForCoacheeasync(MsgRecord);
        if (val)
        {

            coacheeMails.Add(item.EmailID);
            if (item.Parent_Email != null)
            {
                ParentMails.Add(item.Parent_Email);
            }
            if (item.PhoneMail != null)
            {
                PhoneMails.Add(item.PhoneMail);
            }
           
        if (Convert.ToInt32(Session["Role"]) == ConstantData.Role.Coach)
        {
            _repoObjCoach.MessageCreatedNotification(MessageCreatedByCoach.Coachee + Session["user"].ToString(),string.Concat(LinkPageMessageCreated.coachee,item.UserID.ToString()),"",item.CoacheeIdentityID);
        }
        else
        {
            _repoObjCoach.MessageCreatedNotification(MessageCreatedByCoach.alternateCoachee + Session["user"].ToString(),item.CoacheeIdentityID);
        }
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...