我有以下的抽象类:
public abstract class Notification
{
public Notification()
{
this.receivedDate = DateTime.Now.ToUniversalTime();
}
public int Id { get; set; }
public DateTime receivedDate { get; set; }
public bool unread { get; set; }
public virtual ApplicationUser recipient { get; set; }
}
有几个类继承它,例如ProfileViewNotification
和NewMessageNotification
:
public class ProfileViewNotification: Notification
{
public virtual ApplicationUser Viewer { get; set; }
}
public class NewMessageNotification: Notification
{
public virtual Message Message { get; set; }
}
我有以下方法来查询我的数据库,获取所有以给定的
ApplicationUser
为 recipient
的 Notification
:public static List<NotificationApiViewModel> GetNotificationsForUser(string idOfUser)
{
List<NotificationApiViewModel> resultAsApiViewModel = new List<NotificationApiViewModel>();
List<ProfileViewNotification> ofProfileViewNotificationType = null;
List<NewMessageNotification> ofNewMessageNotificationType = null;
try
{
using (var context = new ApplicationDbContext())
{
var query = context.Notifications.Where(c => c.recipient.Id == idOfUser);
ofNewMessageNotificationType = query.OfType<NewMessageNotification>().Any() ?
query.OfType<NewMessageNotification>()
.Include(n => n.recipient)
.Include(n => n.recipient.MyProfile)
.Include(n => n.recipient.MyProfile.ProfileImages)
.Include(n => n.Message)
.Include(n => n.Message.Author)
.Include(n => n.Message.Author.MyProfile)
.Include(n => n.Message.Author.MyProfile.ProfileImages)
.Include(n => n.Message.Recipient)
.Include(n => n.Message.Recipient.MyProfile)
.Include(n => n.Message.Recipient.MyProfile.ProfileImages)
.ToList()
: null;
ofProfileViewNotificationType = query.OfType<ProfileViewNotification>().Any() ?
query.OfType<ProfileViewNotification>()
.Include(n => n.recipient)
.Include(n => n.recipient.MyProfile)
.Include(n => n.recipient.MyProfile.ProfileImages)
.Include(n => n.Viewer)
.Include(n => n.Viewer.MyProfile)
.Include(n => n.Viewer.MyProfile.ProfileImages)
.ToList()
: null;
}
}
catch (Exception ex)
{
//Log issue
}
if (ofNewMessageNotificationType != null)
{
foreach (var n in ofNewMessageNotificationType)
{
resultAsApiViewModel.Add(NotificationApiViewModel.ConvertToApiViewModel(n));
}
}
if (ofProfileViewNotificationType != null)
{
foreach (var n in ofProfileViewNotificationType)
{
resultAsApiViewModel.Add(NotificationApiViewModel.ConvertToApiViewModel(n));
}
}
return resultAsApiViewModel;
}
重要提示,我的所有
ConvertToApiViewModel
方法都不会查询数据库,这就是为什么在原始查询中我使用了这些Include
。另外,上面的内容仅包括两种通知类型,出于简洁考虑,但实际上我有十几种通知。
我的问题是我的方法非常慢。对于一个只有20个通知的用户,它需要超过一分钟的时间才能完成!
有人能告诉我我做错了什么吗?