I'm having a problem with assigning an object inside foreach loop using Entity Framework, I don't know why it's taking very long time (Almost 48 seconds for 1800 items in the loop!!).
Sample Code:
using (var db = new MyEntities())
{
foreach (long r in Recipients) //Recipients has 1800 items.
{
var temp = new DirectMessage();
temp = db.DirectMessages().FirstOrDefault();
temp.SenderProfileImageUrl = "https://www.google.com.sa/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png";
}
}
This simple loop is taking around 45 seconds!!
At testing and debugging, I noticed that this command temp = db.DirectMessages().FirstOrDefault(); is making the delay!
Also, originally it had .Where and .OrderBy using r.ID but I changed it to the simplest way to make sure the delay is not from the filtering.
Update, Original Code:
foreach (long r in Recipients)
{
MsgObj = new AllMsgsClass();
MsgObj.LastMsg = db.DirectMessages.Where(a => (a.SenderID == r || a.RecipientID == r)).OrderByDescending(a => a.CreatedDate).AsNoTracking().FirstOrDefault();
try
{
if (MsgObj.LastMsg.MsgSort == "Sent")
MsgObj.LastMsg.RecipientProfileImageUrl = "https://avatars.io/twitter/" + MsgObj.LastMsg.RecipientScreenName + "/small";
else
MsgObj.LastMsg.SenderProfileImageUrl = "https://avatars.io/twitter/" + MsgObj.LastMsg.SenderScreenName + "/small";
}
catch (Exception dd)
{
string x = dd.Message;
}
MsgObj.SortOrder = Convert.ToDateTime(MsgObj.LastMsg.CreatedDate);
AllMSGsList.Add(MsgObj);
}
Any help would be so appreciated!