开发者

Preserving DataContext, long running operation within Iterating

开发者 https://www.devze.com 2023-03-15 06:08 出处:网络
Following actions needs to be performed: get a view from the database of users that needs to recieve an e-mail

Following actions needs to be performed:

  • get a view from the database of users that needs to recieve an e-mail
  • send this email
  • update the records of the usres with a timestamp the email was send.

This code does as described above but in the wrong order (rough sketch/needs refactoring):

public class MailMessageController
{
  public static IEnumerable<Invitation> GetInvitations()
  {
     using (boDataContext context = new boDataContext())
     {
        // the table where the timestamps have to be set
        Table<Computer> computer = context.GetTable<Computer>();
        // the view that contains the users email addresses
        Table<Invitation> report = context.GetTable<Invitation>();
        // get the view from the database
        IEnumerable<Invitation> items = report.AsEnumerable<Invitation>();
        foreach (Invitation item in items)
        {
           // update the timestamp (not good, the e-mail hasn't been sent)
           Computer c = computer.FirstOrDefault(
                  i => i.ComputerID == item.ComputerID
           );
           if (c != null)
           {
               c.DateInvited = DateTime.Now;
           }
           yield return item;
        }
        context.SubmitChanges(); // <-- this should commit the changes
    }
 }

I send e-mails from this collections via:

foreach(Invitation item in MailMessageController.GetInvitations())
{
  if (SendMessage(item)) // <<-- bool if message was sent successfully
  {
     // here I want to update the database with the timestamp
  }
}

So I need to update the开发者_JAVA百科 database with a timestamp after the e-mail was send succesfully. But it seems that I can't get around the fact that I need to create a context for every instance I need to update.

So this is more of a design issue. How can I get the view from the database, send emails and update the timestamp in the most fluent and less-cost manner?


How about updating the timestamps outside the loop?

var timeStamps = new List<Tuple<DateTime, int>>();
foreach(Invitation item in MailMessageController.GetInvitations())
{
  if (SendMessage(item)) // <<-- bool if message was sent successfully
  {
     timeStamps.Add(new Tuple<DateTime, int>(DateTime.Now, item.ID);
  }
}
UpdateTimeStamps(timeStamps);
0

精彩评论

暂无评论...
验证码 换一张
取 消