0
以下操作需要进行:保留DataContext的,长期运行的内迭代操作
- 从用户的数据库,需要收到一封电子邮件
- 得到一个视图发送这封电子邮件
- 更新带有邮件发送时间戳的usres记录。
此代码之上,但以错误的顺序描述(草图/需要重构):
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
}
}
所以:
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
}
}
我通过发送电子邮件从这个集合我需要在电子邮件发送成功后用时间戳更新数据库。 但似乎我无法解决这个事实,即我需要为每个需要更新的实例创建一个上下文。
所以这是更多的设计问题。 如何从数据库中获取视图,发送电子邮件并以最流畅,更低成本的方式更新时间戳?
从MSDN:“一个DataContext是轻量级的,并不昂贵创建”为什么不更新数据库与循环后的时间戳? – Magnus