需要执行以下操作:
此代码如上所述,但顺序错误(粗略草图/需要重构):
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
}
}
我通过以下方式发送此系列的电子邮件:
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
}
}
所以我需要在电子邮件成功发送后用时间戳更新数据库。 但似乎我无法解决这个问题,即我需要为每个需要更新的实例创建一个上下文。
所以这更像是一个设计问题。 如何从数据库中获取视图,发送电子邮件并以最流畅,最低成本的方式更新时间戳?
答案 0 :(得分:2)
如何更新循环外的时间戳?
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);