我们目前正在开展一个项目,并且我正在开发某种警报/通知系统。基本理念:
有几个问题,每个问题都包含一个Observable Answer对象集合。所有这些项目都保存到SQL Server数据库(我们使用Entity Framework Code First方法)。问题类的重要部分:
public class Question
{
public Question()
{
...
Answers = new ObservableCollection<Answer>();
...
}
public virtual ObservableCollection<Answer> Answers { get; set; }
...Extra stuff omitted
}
我想将一个CollectionChanged Handler添加到Answer实例的ObservableCollection中。我在为该问题创建订阅对象时执行此操作。此Subscription对象被创建并保存在我的manager类中,该类与Database上下文进行通信。执行此操作的方法:
public void CreateQuestionSubscription(int userId, int questionId, NotificationFrequency notificationFrequency)
{
Regular subscriber = _politiciOnlineDbContext.Regulars.SingleOrDefault(r => r.UserId == userId);
Question question = _politiciOnlineDbContext.Questions.SingleOrDefault(q => q.QuestionId == questionId);
if (question == null || subscriber == null) return;
question.Answers.CollectionChanged += new NotifyCollectionChangedEventHandler(CollectionChangedMethod);
QuestionSubscription questionSubscription = new QuestionSubscription()
{
NotificationFrequency = notificationFrequency,
Question = question,
Subscriber = subscriber,
WantsToReceiveEmail = true
};
_politiciOnlineDbContext.QuestionSubscriptions.AddOrUpdate(questionSubscription);
_politiciOnlineDbContext.SaveChanges();
}
private void CollectionChangedMethod(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
Debug.WriteLine("An answer has been added! (sub " + ((Subscription)sender).Subscriber.UserId + "-" + ((QuestionSubscription)sender).Question.QuestionId + ")");
((Subscription)sender).Alerts.Add(new Alert((Subscription)sender, AlertType.QuestionAnswerAdded));
}
}
当我这样做时,Handler确实连接到ObservableCollection的CollectionChanged事件。但它很快就消失了,当我从数据库中获取Question对象时,CollectionChanged事件不包含任何处理程序。
这是相当合乎逻辑的,因为我不知道他们将如何以及在何处得到保存,但这不是我想要实现的目标。我需要处理程序保持连接,当然也可以在数据库中放入和提取对象时。我怎么能这样做?